1

I'm working on a bit of code that adds up all the digits of a number and prints out the sum:

number = #some big 50+ bit number
sum = 0

while number != 0:
    sum += number % 10
    number = int(number/10)

print(sum)

I thought this was a pretty slick solution but when I added print statements to check, it wasn't dividing correctly when the number was very large. I thought that because I was using python 3.8 that I could have arbitrarily large numbers. Is this not the case or am I asking the wrong question?

I tried replacing number = int(number/10) to both number = math.trunc(number/10) and number = math.floor(number/10) and got the same results for both of those as well

2 Answers2

6

The / operator does float division. You need // for integer division. So, use:

number = #some big 50+ bit number
s = 0

while number != 0:
    s += number % 10
    number = int(number//10)

print(s)

Dividing as floats may not work since you lose precision.

GoodDeeds
  • 7,956
  • 5
  • 34
  • 61
3

You can try this way. Convert number into string and loop through string

number = # big number
S = 0
for x in str(number):
  S += int(x)
print(S)
Hirusha Fernando
  • 1,156
  • 10
  • 29