Question
A Pythagorean triplet is a set of three natural numbers, , for which
For example, .
There exists exactly one Pythagorean triplet for which . Find the product .
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))))
Go
package main
import "fmt"
func main() {
var a, b, c, lb int
max := 1000
for a = 1; a < max; a++ {
lb = max - a
for b = a; b < lb; b++ {
c = max - (a + b)
if a*a+b*b == c*c {
fmt.Println(a * b * c)
return
}
}
}
}
$ go build -o pythagorean pythagorean.go
$ time ./pythagorean
real 0m0.001s
user 0m0.000s
sys 0m0.001s
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.376s
user 0m0.368s
sys 0m0.008s
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)
}
}
}
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