Home > front end >  Python digit sum function returns wrong digits on large numbers
Python digit sum function returns wrong digits on large numbers

Time:08-29

The function I wrote is fairly basic: It walks through every digit of num and prints it out. The remainder is then run again until the sample code is finished.

num = 1000000000000000000000000000001
while num > 0:
    curr = num % 10
    num = (num - curr) / 10
    print(curr)

The expected output of this would be 100000000000000000000000000001 (with linebreaks in between). However, it returns the following on the example above:

1622442800000000000000000000001

I suspect this has something to do with the limitations of the long datatype.

How could I handle this problem? Thanks!

CodePudding user response:

It's happening because in Python 3, / means "floating-point" division. Try // instead.

  • Related