Search code examples
fortran

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


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.


Solution

  • 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