Skip to content

Instantly share code, notes, and snippets.

@t-nissie
Last active August 29, 2015 14:24
Show Gist options
  • Save t-nissie/021f09aa327f02d0a710 to your computer and use it in GitHub Desktop.
Save t-nissie/021f09aa327f02d0a710 to your computer and use it in GitHub Desktop.
Fortran: is_power2(a) returns .true. if a is power of 2, i.e. a==2**n.
! is_power2.f -*-f90-*-
! is_power2(a) returns .true. if a is power of 2, i.e. a==2**n.
! Author: Takeshi Nishimatsu
!!
logical function is_power2(a)
implicit none
integer, intent(in) :: a
integer :: x
x = a
if (x<=0) then
is_power2 = .false.
else
do while (mod(x,2).eq.0)
x = x/2
end do
if (x.eq.1) then
is_power2 = .true.
else
is_power2 = .false.
end if
end if
end function is_power2
! is_power2_check.f -*-f90-*-
! check is_power2.f
! Author: Takeshi Nishimatsu
!!
program is_power2_check
implicit none
logical is_power2
external is_power2
if (is_power2(-2)) stop 1
if (is_power2(-1)) stop 2
if (is_power2( 0)) stop 3
if (is_power2( 6)) stop 4
if (is_power2(48)) stop 5
if (.not.is_power2( 1)) stop 6
if (.not.is_power2( 2)) stop 7
if (.not.is_power2( 4)) stop 8
if (.not.is_power2( 8)) stop 9
end program
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment