Search code examples
pythondigits

Python: Summing Digits in a Long Number


I have come up with the following method for summing the digits in number. It seems to work for numbers below about 10^23, but doesn't work for higher numbers. Why does it not work for higher numbers?

x=0
for i in range(0, 5000):
      x+=((number/10**i)//1)%10
print(x)

Solution

  • Leaving aside that this is a very inefficient way to sum the digits, and assuming you're using Python 3, add a conditional print to the loop:

    for i in range(0, 5000):
        piece = ((number/10**i)//1)%10
        if piece:
            print(i, piece)
        x+=((number/10**i)//1)%10
    

    Then you'll be able to see where it's going wrong. Starting with number = 10**24, I get output:

    0 4.0
    1 2.0
    24 1.0
    7.0
    

    You're not expecting those intermediate results, right? Now you only have to figure out why you're getting them ;-)

    The short course is that you're doing floating-point computations when you should be doing integer computations. You get off track immediately (when i is 0):

    >>> 10**24/10**0
    1e+24
    >>> _ // 1
    1e+24
    >>> _ % 10
    4.0
    

    Why is that? Because 10**24 isn't exactly representable as a binary floating-point number:

    >>> from decimal import Decimal
    >>> Decimal(1e24)
    Decimal('999999999999999983222784')
    

    So the exact value of the approximation stored for 1e24 is 999999999999999983222784, and that indeed leaves a remainder of 4 when divided by 10.

    To fix this, just stick to integer operations:

    number = 10**24
    x=0
    for i in range(0, 5000):
        x += number//10**i % 10
    print(x)
    

    That prints 1. Much more efficient is to do, e.g.,

    print(sum(int(ch) for ch in str(number)))