Open In App

Generate Pythagorean Triplets

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++
// C++ program to find all Pythagorean
// Triplets smaller than a given limit
#include<bits/stdc++.h>
using namespace std;

// Function to generate all Pythagorean
// Triplets smaller than limit
vector<vector<int>> pythagoreanTriplets(int limit) {

    // to hold the triplets
    vector<vector<int>> ans;

    for(int a = 1; a<=limit; a++) {
        for(int b = a; b<=limit; b++) {
            for(int c = b; c<=limit; c++) {
                if(a * a + b * b == c * c) {
                    ans.push_back({a,b,c});
                }
            }
        }
    }
    return ans;
}

int main() {
    int limit = 20;
    vector<vector<int>> ans = pythagoreanTriplets(limit);
    for (int i = 0; i < ans.size(); i++) {
        for (int j = 0; j < 3; j++) {
            cout << ans[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
C
// C program to find all Pythagorean
// Triplets smaller than a given limit
#include <stdio.h>

void pythagoreanTriplets(int limit) {

    // to hold the triplets
    int a, b, c;

    for(a = 1; a <= limit; a++) {
        for(b = a; b <= limit; b++) {
            for(c = b; c <= limit; c++) {
                if(a * a + b * b == c * c) {
                    printf("%d %d %d\n", a, b, c);
                }
            }
        }
    }
}

int main() {
    int limit = 20;
    pythagoreanTriplets(limit);
    return 0;
}
Java
// Java program to find all Pythagorean
// Triplets smaller than a given limit
import java.util.*;

class GFG {

    // Function to generate all Pythagorean
    // Triplets smaller than limit
    static List<List<Integer>> pythagoreanTriplets(int limit) {

        // to hold the triplets
        List<List<Integer>> ans = new ArrayList<>();

        for(int a = 1; a <= limit; a++) {
            for(int b = a; b <= limit; b++) {
                for(int c = b; c <= limit; c++) {
                    if(a * a + b * b == c * c) {
                        ans.add(Arrays.asList(a, b, c));
                    }
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int limit = 20;
        List<List<Integer>> ans = pythagoreanTriplets(limit);

        for (List<Integer> triplet : ans) {
            for (int num : triplet) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python program to find all Pythagorean
# Triplets smaller than a given limit

def pythagoreanTriplets(limit):

    # to hold the triplets
    ans = []

    for a in range(1, limit + 1):
        for b in range(a, limit + 1):
            for c in range(b, limit + 1):
                if a * a + b * b == c * c:
                    ans.append([a, b, c])

    return ans

# Driver code
limit = 20
ans = pythagoreanTriplets(limit)

for triplet in ans:
    for num in triplet:
        print(num, end=" ")
    print()
C#
// C# program to find all Pythagorean
// Triplets smaller than a given limit

using System;
using System.Collections.Generic;

class GFG {

    // Function to generate all Pythagorean
    // Triplets smaller than limit
    static List<List<int>> pythagoreanTriplets(int limit) {

        // to hold the triplets
        List<List<int>> ans = new List<List<int>>();

        for(int a = 1; a <= limit; a++) {
            for(int b = a; b <= limit; b++) {
                for(int c = b; c <= limit; c++) {
                    if(a * a + b * b == c * c) {
                        ans.Add(new List<int> { a, b, c });
                    }
                }
            }
        }
        return ans;
    }

    static void Main() {
        int limit = 20;
        List<List<int>> ans = pythagoreanTriplets(limit);

        foreach (List<int> triplet in ans) {
            foreach (int num in triplet) {
                Console.Write(num + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// JavaScript program to find all Pythagorean
// Triplets smaller than a given limit

function pythagoreanTriplets(limit) {

    // to hold the triplets
    let ans = [];

    for(let a = 1; a <= limit; a++) {
        for(let b = a; b <= limit; b++) {
            for(let c = b; c <= limit; c++) {
                if(a * a + b * b === c * c) {
                    ans.push([a, b, c]);
                }
            }
        }
    }
    return ans;
}

// Driver code
let limit = 20;
let ans = pythagoreanTriplets(limit);

for (let triplet of ans) {
    console.log(triplet.join(" "));
}

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
C++
// C++ program to find all Pythagorean
// Triplets smaller than a given limit
#include<bits/stdc++.h>
using namespace std;

// Function to generate all Pythagorean
// Triplets smaller than limit
vector<vector<int>> pythagoreanTriplets(int limit) {

    // to hold the triplets
    vector<vector<int>> ans;

    for(int c = 1; c<=limit; c++) {
        int a = 1, b = c - 1;
        while (a <= b) {
            if (a * a + b * b == c * c) {
                ans.push_back({a,b,c});
                break;
            }
            else if (a * a + b * b < c * c) {
                a++;
            }
            else {
                b--;
            }
        }
    }
    return ans;
}

int main() {
    int limit = 20;
    vector<vector<int>> ans = pythagoreanTriplets(limit);
    for (int i = 0; i < ans.size(); i++) {
        for (int j = 0; j < 3; j++) {
            cout << ans[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
Java
// Java program to find all Pythagorean
// Triplets smaller than a given limit
import java.util.*;

class GFG {

    // Function to generate all Pythagorean
    // Triplets smaller than limit
    static List<List<Integer>> pythagoreanTriplets(int limit) {

        // to hold the triplets
        List<List<Integer>> ans = new ArrayList<>();

        for(int c = 1; c <= limit; c++) {
            int a = 1, b = c - 1;
            while (a <= b) {
                if (a * a + b * b == c * c) {
                    ans.add(Arrays.asList(a, b, c));
                    break;
                }
                else if (a * a + b * b < c * c) {
                    a++;
                }
                else {
                    b--;
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int limit = 20;
        List<List<Integer>> ans = pythagoreanTriplets(limit);
        for (int i = 0; i < ans.size(); i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(ans.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python program to find all Pythagorean
# Triplets smaller than a given limit

def pythagoreanTriplets(limit):

    # to hold the triplets
    ans = []

    for c in range(1, limit + 1):
        a, b = 1, c - 1
        while a <= b:
            if a * a + b * b == c * c:
                ans.append([a, b, c])
                break
            elif a * a + b * b < c * c:
                a += 1
            else:
                b -= 1
    return ans

# Driver code
limit = 20
ans = pythagoreanTriplets(limit)
for i in range(len(ans)):
    for j in range(3):
        print(ans[i][j], end=" ")
    print()
C#
// C# program to find all Pythagorean
// Triplets smaller than a given limit

using System;
using System.Collections.Generic;

class GFG {

    // Function to generate all Pythagorean
    // Triplets smaller than limit
    static List<List<int>> pythagoreanTriplets(int limit) {

        // to hold the triplets
        List<List<int>> ans = new List<List<int>>();

        for(int c = 1; c <= limit; c++) {
            int a = 1, b = c - 1;
            while (a <= b) {
                if (a * a + b * b == c * c) {
                    ans.Add(new List<int> { a, b, c });
                    break;
                }
                else if (a * a + b * b < c * c) {
                    a++;
                }
                else {
                    b--;
                }
            }
        }
        return ans;
    }

    public static void Main() {
        int limit = 20;
        List<List<int>> ans = pythagoreanTriplets(limit);
        for (int i = 0; i < ans.Count; i++) {
            for (int j = 0; j < 3; j++) {
                Console.Write(ans[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// JavaScript program to find all Pythagorean
// Triplets smaller than a given limit

function pythagoreanTriplets(limit) {

    // to hold the triplets
    let ans = [];

    for(let c = 1; c <= limit; c++) {
        let a = 1, b = c - 1;
        while (a <= b) {
            if (a * a + b * b === c * c) {
                ans.push([a, b, c]);
                break;
            }
            else if (a * a + b * b < c * c) {
                a++;
            }
            else {
                b--;
            }
        }
    }
    return ans;
}

// Driver code
let limit = 20;
let ans = pythagoreanTriplets(limit);
for (let i = 0; i < ans.length; i++) {
    for (let j = 0; j < 3; j++) {
        process.stdout.write(ans[i][j] + " ");
    }
    console.log();
}

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. 

C++
// C++ program to generate pythagorean
// triplets smaller than a given limit
#include <bits/stdc++.h>

// Function to generate pythagorean
// triplets smaller than limit
void pythagoreanTriplets(int limit)
{

    // triplet: a^2 + b^2 = c^2
    int a, b, c = 0;

    // loop from 2 to max_limit
    int m = 2;

    // Limiting c would limit
    // all a, b and c
    while (c < limit) {

        // now loop on j from 1 to i-1
        for (int n = 1; n < m; ++n) {

            // Evaluate and print triplets using
            // the relation between a, b and c
            a = m * m - n * n;
            b = 2 * m * n;
            c = m * m + n * n;

            if (c > limit)
                break;

            printf("%d %d %d\n", a, b, c);
        }
        m++;
    }
}

// Driver Code
int main()
{
    int limit = 20;
    pythagoreanTriplets(limit);
    return 0;
}
Java
// Java program to generate pythagorean
// triplets smaller than a given limit
import java.io.*;
import java.util.*;

class GFG {

    // Function to generate pythagorean
    // triplets smaller than limit
    static void pythagoreanTriplets(int limit)
    {

        // triplet: a^2 + b^2 = c^2
        int a, b, c = 0;

        // loop from 2 to max_limit
        int m = 2;

        // Limiting c would limit
        // all a, b and c
        while (c < limit) {

            // now loop on j from 1 to i-1
            for (int n = 1; n < m; ++n) {
                // Evaluate and print
                // triplets using
                // the relation between
                // a, b and c
                a = m * m - n * n;
                b = 2 * m * n;
                c = m * m + n * n;

                if (c > limit)
                    break;

                System.out.println(a + " " + b + " " + c);
            }
            m++;
        }
    }

    // Driver Code
    public static void main(String args[])
    {
        int limit = 20;
        pythagoreanTriplets(limit);
    }
}

// This code is contributed by Manish.
Python
# Python3 program to generate pythagorean 
# triplets smaller than a given limit

# Function to generate pythagorean 
# triplets smaller than limit
def pythagoreanTriplets(limits) :
    c, m = 0, 2

    # Limiting c would limit 
    # all a, b and c
    while c < limits :
        
        # Now loop on n from 1 to m-1
        for n in range(1, m) :
            a = m * m - n * n
            b = 2 * m * n
            c = m * m + n * n

            # if c is greater than
            # limit then break it
            if c > limits :
                break

            print(a, b, c)

        m = m + 1


# Driver Code
if __name__ == '__main__' :
    
    limit = 20
    pythagoreanTriplets(limit)


# This code is contributed by Shrikant13.
C#
// C# program to generate pythagorean
// triplets smaller than a given limit
using System;

class GFG {

    // Function to generate pythagorean
    // triplets smaller than limit
    static void pythagoreanTriplets(int limit)
    {

        // triplet: a^2 + b^2 = c^2
        int a, b, c = 0;

        // loop from 2 to max_limit
        int m = 2;

        // Limiting c would limit
        // all a, b and c
        while (c < limit) {

            // now loop on j from 1 to i-1
            for (int n = 1; n < m; ++n)
            {
                
                // Evaluate and print
                // triplets using
                // the relation between
                // a, b and c
                a = m * m - n * n;
                b = 2 * m * n;
                c = m * m + n * n;

                if (c > limit)
                    break;

                Console.WriteLine(a + " " 
                            + b + " " + c);
            }
            m++;
        }
    }

    // Driver Code
    public static void Main()
    {
        int limit = 20;
        pythagoreanTriplets(limit);
    }
}

// This code is contributed by anuj_67.
JavaScript
<script>

// Javascript program to generate pythagorean
// triplets smaller than a given limit

// Function to generate pythagorean
// triplets smaller than limit
function pythagoreanTriplets(limit)
{
    
    // Triplet: a^2 + b^2 = c^2
    let a, b, c = 0;

    // Loop from 2 to max_limit
    let m = 2;

    // Limiting c would limit
    // all a, b and c
    while (c < limit)
    {
        
        // Now loop on j from 1 to i-1
        for(let n = 1; n < m; ++n)
        {
            
            // Evaluate and print
            // triplets using
            // the relation between
            // a, b and c
            a = m * m - n * n;
            b = 2 * m * n;
            c = m * m + n * n;

            if (c > limit)
                break;

            document.write(a + " " + b + 
                               " " + c + "</br>");
        }
        m++;
    }
}

// Driver code 
let limit = 20;
pythagoreanTriplets(limit);

// This code is contributed by divyesh072019

</script>
PHP
<?php
// PHP program to generate pythagorean 
// triplets smaller than a given limit

// Function to generate pythagorean 
// triplets smaller than limit
function pythagoreanTriplets($limit)
{
    
    // triplet: a^2 + b^2 = c^2
    $a; 
    $b; 
    $c=0;

    // loop from 2 to max_limit
    $m = 2;

    // Limiting c would limit
    // all a, b and c
    while ($c < $limit)
    {
        
        // now loop on j from 1 to i-1
        for ($n = 1; $n < $m; ++$n)
        {
            
            // Evaluate and print
            // triplets using the
            // relation between a, 
            // b and c
            $a = $m *$m - $n * $n;
            $b = 2 * $m * $n;
            $c = $m * $m + $n * $n;

            if ($c > $limit)
                break;

            echo $a, " ", $b, " ", $c, "\n";
        }
        $m++;
    }
}

    // Driver Code
    $limit = 20;
    pythagoreanTriplets($limit);

// This code is contributed by ajit.
?>

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


Next Article
Article Tags :
Practice Tags :

Similar Reads