Reputation: 843
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
Upvotes: 2
Views: 3963
Reputation: 1
Another option to count the number of digits of a big integer is
int(math.ceil(math.log10(big_integer)))
For example:
>>> big_integer=2**100
>>> print int(math.ceil(math.log10(big_integer)))
31
>>> print big_integer
1267650600228229401496703205376
Upvotes: 0
Reputation: 31
Actually the easier method is to use log (or log10) in python. log10 has enough precision for this and can even solve 2**1000000 instantly without taking any space.
from math import log10
ans=int(1000*log10(2))+1
Upvotes: 3
Reputation: 27038
The other answers address how to sum the digits in a large number, but if your question is indeed on how to get the number of digits then just do
largenumber=2*1000
int(math.log(largenumber,10)+1)
or
len(str(largenumber))
Upvotes: 2
Reputation: 226256
To work this problem, use integer math and convert the result to a string:
>>> digits = str(2 ** 1000)
>>> len(digits) # count the digits
302
>>> sum(map(int, digits)) # sum the digits
1366
Upvotes: 0
Reputation: 6582
To calculate 2^1000 in Python use 2**1000
. Using floating point functions like math.log
and math.pow
you are likely to get inaccurate results.
Now, here is how to do it:
l = str(2**1000)
digits = [int(digit) for digit in l]
print sum(digits)
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.
Upvotes: 6
Reputation: 2415
Avoid using double precision and use arbitrary length integers instead:
sum([ int(i) for i in str(2 ** 1000) ])
Upvotes: 0
Reputation: 13356
Use integer arithmetic, int
s in python does not overflow, so no need to do the floating point calculations. Calculate the power yourself:
def pow(a, b):
n = 1
for i in range(b):
n *= a
return a
which is O(n). You can also try the O(lg n) method:
def pow(a, b):
if b == 0:
return 1
temp = pow(a, b/2)
if b % 2 == 0:
return temp * temp
return temp * temp * a
Calculate the sum of digits as you are doing now.
Upvotes: 0
Reputation: 9124
What about using long()?
import math
def power(x):
y_p = 1000 * math.log(x, 10.0)
y = math.pow(10, y_p)
return long(y) # convert to long since we know it is an integral value
if __name__ == "__main__":
ans = power(2)
a = str(ans)
print a
print len(a)
Upvotes: 0