Logo

Programming-Idioms

  • Go
  • C++
  • Fortran
  • Python

Idiom #263 Integer logarithm in base 2

Write two functions log2d and log2u, which calculate the binary logarithm of their argument n rounded down and up, respectively. n is assumed to be positive. Print the result of these functions for numbers from 1 to 12.

import math
def log2d(n):
    return math.floor(math.log2(n))

def log2u(n):
    return math.ceil(math.log2(n))

for n in range(1, 13):
    print(n, log2d(n), log2u(n))

Functions accept both int and float parameters
from math import log2, floor, ceil
log2d = lambda x: floor(log2(x))
log2u = lambda x: ceil(log2(x))
for i in range(1, 13):
    print(i, log2d(i), log2u(i))
program main
  implicit none
  integer :: i
  do i=1,12
     print *,i,log2d(i),log2u(i)
  end do
contains
  integer function log2d (n)
    integer, intent(in) :: n
    log2d = bit_size(n) - 1 - leadz(n)
  end function log2d

  integer function log2u (n)
    integer, intent(in) :: n
    log2u = bit_size(n) - leadz(n-1)
  end function log2u
end program main
log2d :: Double -> Integer
log2d = floor . logBase 2

log2u :: Double -> Integer
log2u = ceiling . logBase 2

main :: IO ()
main = print $ [log2d, log2u] <*> [1..12]

New implementation...
< >
tkoenig