I am currently trying out Project Euler and one of the question is calculate 2^1000, and count the number of digits. I can easily do it for 2^15 but the issue with 2^1000 is that when I calculate it, it’s given in scientific notation, so it’s hard to sum the digits.
import math
def power(x):
y_p=1000*math.log(x,10.0)
y=math.pow(10,y_p)
return y
if __name__=="__main__":
ans=power(2)
a=str(ans)
print a
sum=0
for i in a:
if i == ".":
print "encountered ."
elif i == "e":
break
else:
sum=sum+int(i)
print sum
To calculate 2^1000 in Python use
2**1000. Using floating point functions likemath.logandmath.powyou are likely to get inaccurate results.Now, here is how to do it:
The first line converts the number to a string in base 10 representation.The second line iterates on the characters and transforms the string to a list of digits. And the third prints their sum.