Table of contents
Problem
A Pythagorean triplet is a set of three natural numbers, a < b < 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 abc
.
Problem Description
In a Pythagorean triplet of natural numbers, a < b < c
for which,
$$a^2 + b^2 = c^2$$
Example,
$$3^2 + 4^2 = 9 + 16 = 25 = 5^2$$
In this case a + b + c
is 12
and a * b * c
is 60
Same way, there exists one triplet, where a + b + c = 1000
and we need to find a * b * c
of that triplet.
Approach
Let's approach this problem as finding some triplets where a + b + c = n
.
There are as many different mathematical approaches to solving this(I have known only 2. But Wikipedia has more than that ๐).
The straightforward approach is to loop over a and b to check,
$$a^2 + b^2 = (n โ a โ b)^2$$
And since we have a < b < c
, we use the below formula while looping through a
and b
- a <= (n - 3)/3 & b < (n - a)/2
Solution
const pythagoreanTriplet = n => {
let maxProduct = -1;
for(let a = 1; a <= (n - 3)/3; a++) {
for (let b = a; b <= (n - a)/2 ; b++) {
if( (a*a) + (b*b) === (n-a-b)*(n-a-b)) {
maxProduct = a*b*(n-a-b);
}
}
}
return maxProduct;
}
console.log(pythagoreanTriplet(1000));
You can find my solution on GitHub 09. My GitHub solution is different from the above. To achieve 100% success(all test cases passed) in Hacker Rank, I tweaked a bit using the formula.
If you have another or a better solution, please leave it in the comments below.
For the other Project Euler Solutions, please follow the series Project Euler Solutions in JS.
Thank you!