0

The following program runs into an error because when I divide the large integer by 10 and truncate it, Python does weird math and returns a different number.

# Program to add the digits in an integer
# eg. 463728 would equal 30 ( 4+6+3+7+2+8 )

the_sum = 2**1000

running_tot = 0
sum_length = len(str(the_sum)) # to calculate the length of the integer

i = 0 #initialize iterator

while i < sum_length:
    remainder = the_sum % 10     # Find out the last no. in int.
    running_tot += remainder     # adds the last no. to running total
    the_sum = int(the_sum / 10)  # truncates the last no. for original number
    i += 1                       # increment iterator 
 
print(running_tot)

I would like to know why Python does this?

tripleee
  • 175,061
  • 34
  • 275
  • 318

0 Answers0