Project Euler その13

Problem15

Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

How many such routes are there through a 20×20 grid?

2x2の格子の左上の隅からスタートし、左か下にしか進むことはできない。
右下の隅までのルートはきっかり6つ。

では、20x20の格子ではいくつのルートがあるだろうか?

コード

factorial = lambda z: reduce(lambda x,y: x*y, range(1,z+1))
print factorial(40)/(factorial(20)*factorial(20))

何のことはなく40!/(20!*20!)を計算しているだけ。

Problem17

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?

2^15 は32768であり、それの各桁の和は3 + 2 + 7 + 6 + 8 = 26となる。

2^1000の各桁の和は幾つになるか?

コード

N = 2**1000
S = 0
for i in str(N):
    S += int(i)

print S

多倍長整数のおかげでそのまんま。