Problem
A Pythagorean triplet is a set of three natural numbers, $a \lt b \lt c$,
for which
$$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$.
Answer
1 | 31875000 |
Python1
2
3
4
5
6
7
8
9
10
11
12def compute():
PERIMETER = 1000
for a in range(1, PERIMETER + 1):
for b in range(a + 1, PERIMETER + 1):
c = PERIMETER - a - b
if a * a + b * b == c * c:
# It is now implied that b < c, because we have a > 0
return str(a * b * c)
if __name__ == "__main__":
print(compute())
JavaScript
1 | for (let a = 1; a < 1000; a++) { |
Go1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package 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
}
}
}
}
Ruby1
2
3
4
5
6
7
8
9
10#!/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
Haskell1
2
3main :: 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]
Clojure1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20#!/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))))
Mathematica1
2
3
4
5For[a = 1, a <= 1000, a++,
For[b = a + 1, b <= 1000, b++,
Block[{c = 1000 - a - b},
If[a < b < c && a^2 + b^2 == c^2,
Print[a, " ", b, " ", c, " ", a * b * c]]]]]
Java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27public final class p009 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p009().run());
}
/*
* Computers are fast, so we can implement a brute-force search to directly solve the problem.
* Note that a^2 + b^2 is bounded above by 2*(1000^2), which fits in a Java int type.
*/
private static final int PERIMETER = 1000;
public String run() {
for (int a = 1; a < PERIMETER; a++) {
for (int b = a + 1; b < PERIMETER; b++) {
int c = PERIMETER - a - b;
if (a * a + b * b == c * c) {
// It is now implied that b < c, because we have a > 0
return Integer.toString(a * b * c);
}
}
}
throw new AssertionError("Not found");
}
}