Skip to content

Instantly share code, notes, and snippets.

@hroi
Created February 23, 2010 15:29
Show Gist options
  • Save hroi/312302 to your computer and use it in GitHub Desktop.
Save hroi/312302 to your computer and use it in GitHub Desktop.
; Problem 6
; The sum of the squares of the first ten natural numbers is,
;
; 1^2 + 2^2 + ... + 10^2 = 385
(def natural-numbers (iterate inc 1))
(def squares (map #(* % %) natural-numbers))
(def sum-of-squares
(reduce + (take 10 squares)))
; The square of the sum of the first ten natural numbers is,
;
; (1 + 2 + ... + 10)^2 = 55^2 = 3025
(def square-of-sum
(let [sum (reduce + (take 10 natural-numbers))]
(* sum sum)))
; 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.
(- square-of-sum sum-of-squares)
; Find the difference between the sum of the squares of the first one
; hundred natural numbers and the square of the sum.
(defn sum-of-squares* [n]
(reduce + (take n squares)))
(defn square-of-sum* [n]
(let [sum (reduce + (take n natural-numbers))]
(* sum sum)))
(defn diff [n]
(- (square-of-sum* n) (sum-of-squares* n)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment