Project Euler Problem 6 Solution

Question

The sum of the squares of the first ten natural numbers is,

12+22+...+102=385\displaystyle 1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is,

(1+2+...+10)2=552=3025\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 3025385=26403025 - 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 clojure square_sum.clj
real   0m0.683s
user   0m1.168s
sys    0m0.056s

Go

package 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)
}
$ go build -o square-sum square-sum.go
$ 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