Problem
The sum of the squares of the first ten natural numbers is,
$$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.
Answer
1 | 25164150 |
Python1
2#!/usr/bin/env python
print(sum(range(1, 101))**2 - sum(x**2 for x in range(1, 101)))
JavaScript1
2
3
4
5
6let sum = 0, sumSquares = 0
for (let i = 1; i <= 100; i++) {
sum += i
sumSquares += i * i
}
console.log(sum * sum - sumSquares)
Go1
2
3
4
5
6
7
8
9
10
11
12
13package main
import "fmt"
func main() {
sumSquares, squareSum := 0, 0
for i := 1; i <= 100; i++ {
sumSquares += i * i
squareSum += i
}
squareSum *= squareSum
fmt.Println(squareSum - sumSquares)
}
Ruby1
2#!/usr/bin/env ruby
puts ((1..100).inject(0) {|s,v| s += v})**2 - ((1..100).collect {|x| x**2}.inject(0) { |s,v| s += v})
Haskell1
2
3
4main :: IO ()
main = print $ (s*s) - sqS where
s = sum [1..100]
sqS = sum [i * i | i <- [1..100]]
Clojure1
2
3
4
5
6
7
8
9
10
11#!/usr/bin/env clojure
(defn square [x]
(* x x))
(defn sum-squares [limit]
(apply + (map square (range 1 (+ limit 1)))))
(defn square-sum [limit]
(square (apply + (range 1 (+ limit 1)))))
(println (- (square-sum 100) (sum-squares 100)))
Rust1
2
3
4
5fn main() {
let sum_squares = (1..101).map(|x| x*x).sum::<u64>();
let square_sum = (1..101).sum::<u64>().pow(2);
println!("{}", square_sum - sum_squares);
}
Mathemtica1
2
3
4
5
6
7
8
9(*
* Computers are fast, so we can implement this solution directly without any clever math.
* However for the mathematically inclined, there are closed-form formulas:
* sum = n(n + 1) / 2.
* sum2 = n(n + 1)(2n + 1) / 6.
* Hence sum^2 - sum2 = (n^4 / 4) + (n^3 / 6) - (n^2 / 4) - (n / 6).
*)
n = 100;
Sum[k, {k, n}]^2 - Sum[k^2, {k, n}]
Java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30public final class p006 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p006().run());
}
/*
* Computers are fast, so we can implement this solution directly without any clever math.
* Note that sum^2 is bounded above by (100*100)^2 and sum2 is
* bounded above by 100*(100^2), both of which fit in a Java int type.
*
* However for the mathematically inclined, there are closed-form formulas:
* sum = N(N + 1) / 2.
* sum2 = N(N + 1)(2N + 1) / 6.
* Hence sum^2 - sum2 = (N^4 / 4) + (N^3 / 6) - (N^2 / 4) - (N / 6).
*/
private static final int N = 100;
public String run() {
int sum = 0;
int sum2 = 0;
for (int i = 1; i <= N; i++) {
sum += i;
sum2 += i * i;
}
return Integer.toString(sum * sum - sum2);
}
}