projecteuler_problem6

 15th March 2024 at 12:25pm

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Easy stuff. Only as I add this exercise (which I did later than problem 5 do I realise that iota is much saner than using a range construct.

(import test)
(import (only srfi-1
			  iota))

; Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

; retrieves the square of the sum of naturals from 1 to (including) n
; Integer -> Integer
(define (square-of-sum n)
  (expt (foldr + 0 (iota n 1)) 2))
(test #t (= 1 (square-of-sum 1)))
(test #t (= 36 (square-of-sum 3)))

; retrieves the sum of the squares of naturals from 1 to (including) n
; Integer -> Integer
(define (sum-of-squares n)
  (foldr (lambda (x y) (+ (expt x 2) y)) 0 (iota n 1)))
(test #t (= 1 (sum-of-squares 1)))
(test #t (= 14 (sum-of-squares 3)))


(define (solve-problem-6 n)
  (- (square-of-sum n) (sum-of-squares n)))
(test #t (= 2640 (solve-problem-6 10)))

(print (solve-problem-6 100))

The Project solution for this is a great example on how mathematics can produce a solution that is much more elegant and wise. There's few bigger pleasures in life than looking at a problem and finding such a better approach (case in point: a couple of days ago, a friend of mine let me know of an interview question that he bruteforced, and to which I was able to derive a solution using only linear equations — one that even missed the point of this being a known series).

Anyway, there's also a formula that yields the sum of squares (which is derived in the problem solution), although its derivation starts in the lines of «one could guess the formula is a polynomial». Why would it be so, I wonder?