Python digit sum function returns wrong digits on large numbers

Question:

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!

Asked By: cubexy

||

Answers:

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

Answered By: Ecir Hana
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.