Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000.

Project Euler Problem 9: 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.
Find the product abc.

Solution: The problem involves finding a triplet which meets two conditions

a2 + b2 = c2
and
a + b + c = 1000.

We do this by finding c value by getting square root of a2 + b2. Now for the a,b and c value we check if a + b + c = 1000. If this condition is met, we find the product of a,b and c. This is the solution of our problem.


Java Program to find the only Pythagorean triplet, {a, b, c}.


public class FindPythagoreonTriplet {
public static int findPythagonTriplet(){
int k=0;
for(int i=1;i<1000;i++){
for(int j=i+1;j<999;j++){
k = (int) Math.sqrt(i*i + j*j);
if(i+j+k==1000 && i<j && j<k){
if(i*i+j*j==k*k)
return i*j*k;
}
}
}
return 0;
}
public static void main(String [] args){
System.out.print(findPythagonTriplet());
}
}

Happy Coding !!!

Leave a Reply

Your email address will not be published. Required fields are marked *