VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-pythagorean-triplets/

⇱ Generate Pythagorean Triplets - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate Pythagorean Triplets

Last Updated : 23 Jul, 2025

Given a positive integer limit, your task is to find all possible Pythagorean Triplet (a, b, c), such that a <= b <= c <= limit.

Note: A Pythagorean triplet is a set of three positive integers a, b, and c such that a2 + b2 = c2.

Input: limit = 20
Output: 3 4 5
5 12 13
6 8 10
8 15 17
9 12 15
12 16 20
Explanation: All the triplets are arranged in the format (a, b, c), where a2 + b2 = c2.

[Naive Approach] - Using Nested Loops - O(n ^ 3) Time and O(1) Space

The idea is to use nested loops to generate all possible combinations of a, b, and c. For each combination check if a2 + b2 = c2, if the condition satisfies store the triplet, else move to next combination.


Output
3 4 5 
5 12 13 
6 8 10 
8 15 17 
9 12 15 
12 16 20 

Time Complexity: O(n3), where n is representing the limit.
Space Complexity: O(1)

[Expected Approach] - Using Two Pointers - O(n ^ 2) Time and O(1) Space

The idea is to use Two Pointers to generate combinations of a & b in linear time, and check if a2 + b2 = c2. To do so, iterate through all values of c from 1 to limit, and set a = 1, and b = c - 1. At each iteration there are three possibilities:

  • if a2 + b2 > c2: Decrease the value of b by 1.
  • if a2 + b2 < c2: Increase the value of a by 1.
  • if a2 + b2 = c2: Store the triplet

Output
3 4 5 
6 8 10 
5 12 13 
9 12 15 
8 15 17 
12 16 20 

Time Complexity: O(n2), where n is representing the triplets.
Space Complexity: O(1)

[Alternate Approach] - Using Mathematics

Note: The below given method doesn't generate all triplets smaller than a given limit. For example "9 12 15" which is a valid triplet is not printed by above method.

The idea is to use square sum relation of Pythagorean Triplet that states that addition of squares of a and b is equal to square of c. We can write these numbers in terms of m and n such that,

a = m2 - n2
b = 2 * m * n
c = m2 + n2
because,
a2 = m4 + n4 – 2 * m2 * n2
b2 = 4 * m2 * n2
c2 = m4 + n4 + 2* m2 * n2

We can see that a2 + b2 = c2, so instead of iterating for a, b and c we can iterate for m and n and can generate these triplets. 


Output
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20

Time complexity of this approach is O(√n) where n is the given limit. We are iterating until c <= limit ,where c = m^2 + n^2. Thus the iteration will take place approximately sqrt(limit) times.
Auxiliary space: O(1) as it is using constant space for variables
References:
https://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples

Comment
Article Tags:
Article Tags: