python-2 ^ 1000的数字总和?

时间:2018-07-15 06:34:22

标签: python

这是我在python中的代码,但根据projecteuler.net,它给出的答案不正确。

a = 2**1000
total = 0
while a >= 1:
    temp = a % 10
    total = total + temp
    a = int(a/10)
print(total)

它的输出为1189。我犯了一些错误吗?

1 个答案:

答案 0 :(得分:7)

您的逻辑很好。问题是2 ** 1000太大,以至于所有数字都无法放入浮点数,因此当您执行a = int(a/10)时,数字会四舍五入。 Python float仅具有53位精度,您可以在官方教程文章Floating Point Arithmetic: Issues and Limitations和Wikipedia:Double-precision floating-point format中进行阅读。另请参见Is floating point math broken?

这是2 ** 1000

  

1071508607186267320948425049069068108105614048117055336074437503883703510511249361221983198378815695858127594672917553146825187145285692314043598457757469857480393456777482423098542107460506236237114187795418215304304498498358194126739876755916554394607706692457

但是print(format(2**1000 / 10, 'f'))给了我们这个:

  

10715086071862673804291013881713243224839047377015560126941584547461294133558104951308246652318707999343272527638071704171360968934112360617818675792660857920266800215782081298609410784046320320952952518115872872212230792602542079736499862650266972290981776023900789094345

您可以看到10715086071862673之后数字开始出现错误。

因此,您需要使用整数算术,它在Python中具有任意精度(仅受Python可以访问的内存量限制)。为此,请使用// floor division运算符。

a = 2**1000
total = 0
while a >= 1:
    temp = a % 10
    total = total + temp
    a = a // 10
print(total)

输出

1366

我们可以使用augmented assignment运算符来简化代码。

a = 2**1000
total = 0
while a:
    total += a % 10
    a //= 10
print(total)

这是一种更快的方法。将a转换为字符串,然后将每个数字转换回int并求和。我使用位移来计算a,因为它比取幂快。

print(sum(int(u) for u in str(1 << 1000)))