## Question

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,

$\displaystyle (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.

## Clojure

#!/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)))
$time ./square-sum real 0m0.001s user 0m0.000s sys 0m0.000s ## Haskell main :: IO () main = print$ (s*s) - sqS where
s = sum [1..100]
sqS = sum [i * i | i <- [1..100]]
$ghc -O2 -o squareSum squareSum.hs$ time ./squareSum
real   0m0.001s
user   0m0.000s
sys    0m0.000s

## JavaScript

let sum = 0, sumSquares = 0
for (let i = 1; i <= 100; i++) {
sum += i
sumSquares += i * i
}
console.log(sum * sum - sumSquares)
$time node --use-strict --harmony-destructuring square-sum.js real 0m0.084s user 0m0.072s sys 0m0.012s ## Python #!/usr/bin/env python print(sum(range(1, 101))**2 - sum(x**2 for x in range(1, 101))) $ time python3 square_sum.py
real   0m0.019s
user   0m0.016s
sys    0m0.000s

## Ruby

#!/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})
\$ time ruby square_sum.rb
real   0m0.027s
user   0m0.024s
sys    0m0.000s

Questions? Comments? Send me an email: z@chdenton.com