英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论