0

While solving Project Euler problems with Python (which I am a beginner at), I got this following error. The question is to find the sum of the digits of 2^1000. For that I wrote the following code :

sum=0
x=2**1000
while(x):
  sum += x%10
  print(sum) #Just to check whats happening
  x /= 10

print("\n"*5)
print("Sum = ",sum)

For this, I get decimal added up somewhere in between.

Output :

6
10.0
10.0 
12.0
16.0

....

1116.0
1122.0
1131.625  #Why does the decimal get added?
1138.59375

 .....

 1181.495136589947
 1186.5812084526442
 1188.089815638914
 1195.240676357541
 1195.9557624294036
 1197.0272710365898
 1197.1344218973084
 1197.1451369833803
 1197.1462084919874

 .....
 1197.1463275484991 #This number gets repeated a lot of times
 1197.1463275484991
 1197.1463275484991



 Sum = 1197.1463275484991

Please explain what's going on and help.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

2

Use integer division instead of floating point:

x //= 10
Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • Well, Wow! That worked. Could you explain how the two operators are different? –  Dec 09 '14 at 19:08
  • The regular division will yield the fractional result ("exact" division). The integer division will give only the integer part of the result (rounded down to closest integer). – Eugene Sh. Dec 09 '14 at 19:15
  • See [In Python, what is the difference between '/' and '//' when used for division?](http://stackoverflow.com/q/183853/1029516) – Cavaz Dec 09 '14 at 19:24
0

Do not know if you're looking for an alternative implementation, but this might be more straightforward if you don't want to risk crossing over into floating point land.

# Python 2.7
x = str(2**1000)
print sum([int(i) for i in x])
rchang
  • 5,150
  • 1
  • 15
  • 25
  • Thanks for that. I am new to python, and I coming from the bizarre land of C and C++. So this is what I used in C and so I implemented same logic in Python. –  Dec 09 '14 at 19:13