Project Euler with Ruby on WSL [Problem 6]

ネタばれあり

ですよっと

問題

The sum of the squares of the first ten natural numbers is,  \displaystyle 1^2+2^2+...+10^2=385 The square of the sum of the first ten natural numbers is,  (1+2+...+10)^2=55^2=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.

私訳

1 から 100 までの自然数の、(和の2乗)-(2乗和) を求めよ

解答方針

中学生時代が懐かしいですねぇ。  \displaystyle
 \sum_{i=1}^n i = \frac{n(n+1)}{2}  \displaystyle
 \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} を思い出せば、問われているのは

 \displaystyle
\left( \sum_{i=1}^n i \right)^2 - \sum_{i=1}^n i^2 =  \left( \frac{n(n+1)}{2} \right)^2 -  \frac{n(n+1)(2n+1)}{6}

 \displaystyle
= \frac{n(n+1)}{2} \left( \frac{n(n+1)}{2} - \frac{2n+1}{3} \right) = \frac{n(n+1)}{2} \frac{3n^2+3n-4n-2}{6}
 \displaystyle
= \frac{n(n+1)}{2} \frac{3n^2-n-2}{6} = \frac{(n-1)n(n+1)(3n+2)}{12}

ということになります。 試しに 10 を入れてみると 9101132/12 = 310118 = 2640 で正しそうですね。