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.

## 5 comments:

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! :-)

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

good job , thanks man !I see no reason for the math.floor() call; the int() truncates just fine. Am I missing something?

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, ...

(See http://bugs.python.org/issue6765)

Post a Comment