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

Henning Thielemann lemming at henning-thielemann.de
Tue Aug 25 10:11:00 EDT 2009

On Sat, 22 Aug 2009, Bulat Ziganshin wrote:

> Hello Roberto,
> Saturday, August 22, 2009, 9:19:26 PM, you wrote:
>> I want to calculate the number of digits of a positive integer. I was
> fastest way
> digits = iterate (`div` 10) >>> takeWhile (>0) >>> length

This needs quadratic time with respect to the number of digits, doesn't 
it? If (show . length) is not fast enough, I would try to catch the 
magnitude by repeated squaring of 10. If you have found a 'k' with
    10^(2^k) <= n < 10^(2^(k+1))
  then you can start to find the exact number of digits with bisection.

More information about the Haskell-Cafe mailing list