Find the only Pythagorean triplet which sums to get 1000
A Pythagorean triplet consists of 3 numbers say x, y and z such that x < y < z and x^2 + y^2 = z^2.
The task is to find a triplet which satisfies the equation x + y + z = 1000
(defn sqr [x]
(* x x))
(defn triplets [n]
(loop [x 1 y 2 z (- n 3) acc '()]
(cond
(>= x z) acc
(>= y z) (recur (inc x) (+ 2 x) (- n (+ 3 x x)) acc)
:else (recur x (inc y) (dec z) (cons (list x y z) acc)))))
triplets generates all possible triplets (x, y, z) where x + y + z = 1000 and x < y < z
After this all that needs to be done is
(apply * (first (filter #(let [[a b c] %] (= (+ (sqr a) (sqr b)) (sqr c))) (triplets 1000)))
The let construct in this case has new syntax
(let [[a b c] '(1 2 3)]
(...))
This is known as destructuring, this syntax binds a, b and c to 1, 2 and 3 respectively.
Advertisement