Scala で Project Euler Problem 6
最初の10個の自然数について, その二乗の和は,
12 + 22 + ... + 102 = 385
最初の10個の自然数について, その和の二乗は,
(1 + 2 + ... + 10)2 = 3025
これらの数の差は 3025 - 385 = 2640 となる.
同様にして, 最初の100個の自然数について二乗の和と和の二乗の差を求めよ.
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.
単純な加算
scala> var i = (1 to 10).sum i: Int = 55 scala> i = i * i i: Int = 3025 scala> var j = (1 to 10).map(n => n * n).sum j: Int = 385 scala> i - j res0: Int = 2640
scala> i = (1 to 100).sum i: Int = 5050 scala> i = i * i i: Int = 25502500 scala> j = (1 to 100).map(n => n * n).sum j: Int = 338350 scala> i - j res1: Int = 25164150
数列の和の公式
scala> i = 10 * (10 + 1) / 2 i: Int = 55 scala> i = i * i i: Int = 3025 scala> j = 10 * (10 + 1) * (2 * 10 + 1) / 6 j: Int = 385 scala> i - j res2: Int = 2640
scala> i = 100 * (100 + 1) / 2 i: Int = 5050 scala> i = i * i i: Int = 25502500 scala> j = 100 * (100 + 1) * (2 * 100 + 1) / 6 j: Int = 338350 scala> i - j res3: Int = 25164150 scala>