Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.
The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025.
The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385.
Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640.
Problem 6 at Project Euler http://projecteuler.net/problem=6
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
(ns difference-of-squares-test (:require [clojure.test :refer [deftest is]] [difference-of-squares :as dos])) (deftest square-of-sum-to-5 (is (= 225 (dos/square-of-sum 5)))) (deftest sum-of-squares-to-5 (is (= 55 (dos/sum-of-squares 5)))) (deftest difference-of-squares-to-5 (is (= 170 (dos/difference 5)))) (deftest square-of-sum-to-10 (is (= 3025 (dos/square-of-sum 10)))) (deftest sum-of-squares-to-10 (is (= 385 (dos/sum-of-squares 10)))) (deftest difference-of-squares-to-10 (is (= 2640 (dos/difference 10)))) (deftest square-of-sum-to-100 (is (= 25502500 (dos/square-of-sum 100)))) (deftest sum-of-squares-to-100 (is (= 338350 (dos/sum-of-squares 100)))) (deftest difference-of-squares-to-100 (is (= 25164150 (dos/difference 100))))
(ns difference-of-squares) (defn square [x] (* x x)) (defn sum-of-squares [n] (->> (range (inc n)) (map square) (reduce +))) (defn square-of-sum [n] (->> (range (inc n)) (reduce +) square)) (defn difference [n] (- (square-of-sum n) (sum-of-squares n)))
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.