Project Euler Problem 6 Solution

Question

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.

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.896s
user   0m1.689s
sys    0m0.095s

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.001s

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.002s
user   0m0.002s
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 square-sum.js
real   0m0.052s
user   0m0.044s
sys    0m0.009s

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.016s
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.038s
user   0m0.030s
sys    0m0.008s

Rust

fn 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);
}
$ rustc -C target-cpu=native -C opt-level=3 -o squaresum squaresum.rs
$ time ./squaresum
real   0m0.001s
user   0m0.000s
sys    0m0.001s