VOOZH about

URL: https://www.geeksforgeeks.org/dsa/pythagorean-triplet-with-given-sum-using-single-loop/

⇱ Find Pythagorean Triplet with given sum using Mathematical Formula - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Pythagorean Triplet with given sum using Mathematical Formula

Last Updated : 12 Jul, 2025

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.

Using Mathematical Formula- O(n) Time and O(1) Space

We know that the sum of all the elements in a valid triplet is equal to the given target and it is a Pythagorean triplet. So, we have two equations:
a + b + c = target ............. (1)
a2 + b2 = c2 ............ (2)

From the first equation, calculate b and substitute it into the second equation:
b = target - a - c
a2 + (target - a - c)2 = c2

Now, simplifying the second equation:
=> a2 + (target2 + a2 + c2 - 2*target*a + 2*a*c - 2*target*c) = c2
=> 2*a2 + target2 - 2*target*a - 2*c*(target-a) = 0

Calculating the value of c in terms of a:
=> 2*c*(target-a) = 2*a2 + target2 - 2*target*a
=> c = (2*a2 + target2 - 2*target*a) / 2*(target-a)

Next, we will calculate the value of c for each possible value of a, which ranges from 1 to target - 2. To ensure that c has valid values, the denominator 2*(target-a) must be non-zero and must divide the numerator (2*a2 + target2 - 2*target*a) completely.

After that, we can calculate the value of b by subtracting a and c from the target. The triplet {a, b, c} will certainly be a Pythagorean triplet having sum equal to the given target.


Output
10 24 26
15 20 25

Related Articles:

Comment
Article Tags:
Article Tags: