Question

A Pythagorean triplet is a set of three natural numbers, $a \lt b \lt c$, for which

$\displaystyle a^2 + b^2 = c^2$

For example, $3^2 + 4^2 = 9 + 16 = 25 = 5^2$.

There exists exactly one Pythagorean triplet for which $a + b + c = 1000$. Find the product $a \times b \times c$.

Clojure

#!/usr/bin/env clojure
(defn square [n]
(* n n))

(defn triple? [a b c]
(and
(and (> a 0) (> b 0) (> c 0))
(and (< a b) (< b c))
(= (+ (square a) (square b)) (square c))))

(defn candidates [limit]
(for [a (range 1 (inc limit))
b (range a (inc limit))
c (range b (inc limit))
:when (and
(= (+ a b c) 1000)
(triple? a b c))]
(list a b c)))

(println (reduce * (first (candidates 500))))
$time ./pythagorean real 0m0.001s user 0m0.000s sys 0m0.000s Haskell main :: IO () main = print$ head [a*b*c | a <- [1..500], b <- [a..500], c <- [b..500],
a+b+c == 1000, a*a + b*b == c*c]
$ghc -O2 -o pythagorean pythagorean.hs$ time ./pythagorean
real   0m0.392s
user   0m0.388s
sys    0m0.000s

JavaScript

for (let a = 1; a < 1000; a++) {
for (let b = a, lb = 1000 - a; b < lb; b++) {
const c = 1000 - (a + b)
if (a * a + b * b === c * c) {
return console.log(a * b * c)
}
}
}
$time node --use-strict --harmony-destructuring pythagorean.js real 0m0.068s user 0m0.056s sys 0m0.008s Ruby #!/usr/bin/env ruby for a in (1..500) for b in (a..500) for c in (b..500) if a**2 + b**2 == c**2 and a+b+c == 1000 puts a*b*c end end end end $ time ruby pythagorean-triples.rb
real   0m3.532s
user   0m3.440s
sys    0m0.000s