![]() |
VOOZH | about |
Given a positive integer target, the task is to find all Pythagorean Triplets whose sum of the elements is equal to the given target. A triplet {a, b, c} is considered a Pythagorean triplet if it satisfies the condition a2 + b2 = c2.
Examples :
Input: target = 60
Output: {{10, 24, 26}, {15, 20, 25}}
Explanation: There are two Pythagorean triplets: {10, 24, 26} and {15, 20, 25}, both having a sum equal to 60.Input : target = 4
Output : {}
Explanation: No Pythagorean triplet exists with a sum of 4.
Table of Content
A simple solution is to generate all possible triplets using three nested loops and for every triplet, check if it is a Pythagorean Triplet and the sum of its elements is equal to given target.
10 24 26 15 20 25
This approach is an optimization to the previous one. In this, we run two nested loops to generate all possible values of first two elements of the triplet. The third element can be found by subtracting these values from the given target. We then check whether these elements form a Pythagorean triplet.
10 24 26 15 20 25
We know that the sum of all the elements in a valid triplet is equal to the given target, i.e., a + b + c = target, and it is a Pythagorean Triplet, i.e., a2 + b2 = c2. Now, we can derive the value of c in terms of variable a using these two equations. Then, for all possible values of a, we calculate the corresponding valid c values. Finally, values of b can be found by subtracting a and c from the target.
You can refer to this article for complete implementation of this approach - Find Pythagorean Triplet with given sum using Mathematical Formula.