Friday, 29 August 2008

Counting digits

def digits(x):
""" Return amount of digits of x. """
return int(math.floor(math.log10(x)) + 1)
Because I needed to create an efficient algorithm to count the amount of digits of a number, I have come up with the one you can read above. It is a bit slower than len(str(x)) for small numbers, but a lot faster with large ones.
Another example on how a good algorithm beats processing power.


meisterluk said...

I needed an algorithm for projecteuler problem #41. Therefore I wrote a small algorithm. I compared it with yours:
* Your algo is faster
* Your algo works with floating-point-numbers

So... Well done, segfaulthunter! :-)

Anonymous said...

Awesome. I'm doing Project Euler as well. Thanks for the algo!

mathck said...

good job , thanks man !

Anonymous said...

I see no reason for the math.floor() call; the int() truncates just fine. Am I missing something?

Anonymous said...

Thanks for the code!

I met a strange problem trying to implement this myself. I coded almost the same, but used log(x,10) instead of log10(x) which causes wrong values for 1000,1000000, ...