[Haskell-cafe] How to calculate de number of digits of an integer? (was: Is logBase right?)

Uwe Hollerbach uhollerbach at gmail.com
Wed Aug 26 10:42:06 EDT 2009


Here's my version... maybe not as elegant as some, but it seems to
work. For base 2 (or 2^k), it's probably possible to make this even
more efficient by just walking along the integer as stored in memory,
but that difference probably won't show up until at least tens of
thousands of digits.

Uwe

ilogb :: Integer -> Integer -> Integer
ilogb b n | n < 0      = ilogb b (- n)
          | n < b      = 0
          | otherwise  = (up 1) - 1
  where up a = if n < (b ^ a)
                  then bin (quot a 2) a
                  else up (2*a)
        bin lo hi = if (hi - lo) <= 1
                       then hi
                       else let av = quot (lo + hi) 2
                            in if n < (b ^ av)
                                  then bin lo av
                                  else bin av hi

numDigits n = 1 + ilogb 10 n

[fire up ghci, load, etc]

*Main> numDigits (10^1500 - 1)
1500
*Main> numDigits (10^1500)
1501


More information about the Haskell-Cafe mailing list