Fortran函数用于确定一个整数是否是2的幂或不是。

huangapple go评论50阅读模式
英文:

Fortran function to determine if an integer is a power of 2 or not

问题

我正在尝试编写一个Fortran函数,用于确定一个整数是否是2的幂。这段代码在2^28之前有效,但在2^29时失败:

real(kind(1.q0)) elemental function fractional_part(x)
real(kind(1.q0)), intent(in) :: x
fractional_part = x - floor(x)
end function fractional_part

program frac
implicit none

real(kind(1.q0)) :: fractional_part
integer :: ii
logical :: pof2

read(5,*) ii
pof2 = (fractional_part(log(real(ii,16))/log(2.q0)) == 0.0q0)
if(pof2) write(6,*) ii

end

不幸的是,这个代码依赖于将整数转换为real(16)和log函数,这可能会引入噪音。

英文:

I am trying to write a function in Fortran which will conclusively determine whether an integer is a power of 2 or not. This code works up to 2^28 but fails for 2^29:

 real(kind(1.q0)) elemental function fractional_part(x)
 real(kind(1.q0)), intent(in) :: x
 fractional_part = x-floor(x)
 end function fractional_part

 program frac
 implicit none

 real(kind(1.q0)) :: fractional_part
 integer :: ii
 logical :: pof2

 read(5,*) ii
 pof2 = (fractional_part(log(real(ii,16))/log(2.q0)) == 0.0q0)
 if(pof2) write(6,*) ii

 end

Unfortunately it relies on conversion of the integer to real(16) and the log function which is bound to have noise.

答案1

得分: 7

如果您的输入是非负的,您可以使用popcnt()函数来计算位数。

program test
   integer i
   do i = 1, 2 ** 30
      if ( popcnt(i) == 1 ) print *, i
   end do
end program test
英文:

If your input is non-negative you can just count bits with popcnt().

program test
   integer i
   do i = 1, 2 ** 30
      if ( popcnt(i) == 1 ) print *, i
   end do
end program test

huangapple
  • 本文由 发表于 2023年3月15日 18:59:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定