Project Euler : Problem 9 - Special Pythagorean triplet
Problem Statement : Special Pythagorean triplet
Problem 9 : 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 .
Concept and Theory
First of all I want you to read about Pythagorean triplets, if you haven’t.
Approach 1
From Pythagorus Theorem we know,
and we are given to satify,
Substituing this value in Pythagorus Theorem we will get,
We can see that there is something odd about the above equation that is in denominator. But its fine as numerator will also be negative then for .
So, we just have to iterate over from to to find integral values of .
Approach 1 code
/**
* A function for Project Euler problem 9
*
* @param n
* maximum sum of a,b and c
*
* @return the maximum product
*/
public static long specialPythagoreanTriplet(int n) {
long maxProduct = -1;
for (int a = 1; a < n / 2; a++) {
int numerator = n * (n - 2 * a);
int denominator = 2 * (n - a);
if (numerator % denominator == 0) {
int b = numerator / denominator;
int c = n - a - b;
long tempProduct = a * b * c;
if (tempProduct > maxProduct) {
maxProduct = tempProduct;
}
}
}
return maxProduct;
}
Without coding
I fount this beautiful approach by a person, , on ProjectEuler exploiting on Pythagorean triplets generation.
Test Your Skills
Wanna try a harder version of the above problem ? Check this HackerRank problem.
Solution
The solution will remain same as given in the above mentioned post, , you just need to call it for each test case.
Leave a Comment
Your email address will not be published. Required fields are marked *