In this blog post we will be looking at problem 9 of Project Euler and we will program a solution in Java.
The problem of Project Euler found here, below is the problem for quick lookup.
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
-Project Euler problem 9
Find the product abc.
Let’s summarize the rules.
- a < b < c
- a^2 + b^2 = c^2
- a + b + c = 1000
So let’s start defining the program! We need two for loops. If we make the first for loop ‘a’ and the second ‘b’ we can get c with some math:
c = 1000 – a – b
Because of the last rule where a, b and c add up to 1000. We can then check if a^2 + b^2 = c^2 and if it is print the result.
for (int a = 1; a < 1000 / 3; a++) {
for (int b = a; b < 1000 / 2; b++) {
int c = 1000 - a - b;
if (a*a + b*b == c*c) {
System.out.println("a:" + a);
System.out.println("b:" + b);
System.out.println("c:" + c);
System.out.println(a * b * c);
}
}
}
There are some optimizations in the loop condition in the 2 for loops. Since a has to be smaller than b and c we can divide the loop condition of loop A by 3 leaving you with a max of 333. The same for loop B where we divide by 2 leaving you with a max of 500. Because of the a < b < c rule you can assume this. We initialize b to the current value of a because of the same rule.
Check out the ‘Project Euler in Java’ page for more solutions!
That was Project Euler problem 9 in Java!