Project Euler Problem 006
http://projecteuler.net/index.php?section=problems&id=6
The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
後者の式はエジソンの逸話の式を2乗すればよい、前者の方は分からなかったので単純にループしながら加算した。
def f(n): def f1(n): return sum([i * i for i in range(1, n + 1)]) def f2(n): m = n * (n + 1) >> 1 return m * m return f2(n) - f1(n) print f(100)
答え: 25502500 - 338350 = 25164150
解説を見ると後者の値は下の式で求められる。
解説の手順を試すと確かにOKなのは分かるけど、
def f2(n): return (2 * n + 1) * (n + 1) * n / 6
最初の
がどこから出てきたのか分からなかった。むぅ。