The Wayback Machine - https://web.archive.org/web/20241005050028/https://www.geeksforgeeks.org/generate-pythagorean-triplets/
Open In App

Generate Pythagorean Triplets

Last Updated : 12 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Pythagorean triplet is a set of three positive integers a, b and c such that a2 + b2 = c2. Given a limit, generate all Pythagorean Triples with values smaller than given limit.

Input : limit = 20
Output : 3 4 5
         8 6 10
         5 12 13
         15 8 17
         12 16 20

A Simple Solution is to generate these triplets smaller than given limit using three nested loop. For every triplet, check if Pythagorean condition is true, if true, then print the triplet. Time complexity of this solution is O(limit3) where ‘limit’ is given limit.

An Efficient Solution can print all triplets in O(k) time where k is number of triplets printed. The idea is to use square sum relation of Pythagorean triplet, i.e., addition of squares of a and b is equal to square of c, we can write these number 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. 

Below is the implementation of above idea :  

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.


Python3




# 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.


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.
?>


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>


Output

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

Time complexity of this approach is O(k) where k is number of triplets printed for a given limit (We iterate for m and n only and every iteration prints a triplet)
Auxiliary space: O(1) as it is using constant space for variables

Note: The above 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. Thanks to Sid Agrawal for pointing this out. 
References: 
https://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples



Previous Article
Next Article

Similar Reads

Check if a Lexicographical Pythagorean Triplets exists in range [0, K) of lexicographically largest string
Given a string str and a positive integer K. The task is to find if there exist a Pythagorean Triples in the first window of size K of a string which have the same characters as str but is largest in lexicographical order. Note: Every character is in lower case and consider the following values for each alphabet to check if there exist Pythagorean
8 min read
Twin Pythagorean triplets in an array
Given an array of integers arr[], the task is to check if there is a Twin Pythagorean Triplet in the array. A Twin Pythagorean Triplet is a Pythagorean triplet (a, b, c) for which two values are consecutive integers. The first few twin triples are (3, 4, 5), (5, 12, 13), (7, 24, 25), (20, 21, 29), (9, 40, 41), (11, 60, 61), (13, 84, 85), (15, 112,
13 min read
Pythagorean Quadruple
Given four points, check whether they form Pythagorean Quadruple. It is defined as a tuple of integers a, b, c, d such that [Tex]a^2 + b^2 + c^2 = d^2 [/Tex]. They are basically the solutions of Diophantine Equations. In the geometric interpretation it represents a cuboid with integer side lengths |a|, |b|, |c| and whose space diagonal is |d| . The
4 min read
Check if a number is a Pythagorean Prime or not
Given a positive integer N, check if it is Pythagorean prime or not. If it is a Pythagorean prime, print 'Yes' otherwise print 'No'.Pythagorean primes : A prime number of the form 4*n + 1 is a Pythagorean prime. It can also be expressed as sum of two squares. Pythagorean primes in the range 1 - 100 are: 5, 13, 17, 29, 37, 41, 53, 61, 73, 89, 97 Exa
6 min read
Possible pairs forming a Pythagorean Triple with a given value
Given an integer C, the task is to find all possible pairs (A, B) in range [1, C) such that: A2 + B2 = C2A < B Examples: Input: C = 5 Output:(3, 4) Explanation: (3)2 + (4)2 = 9 + 16 = 25 = 52 Input: C = 25 Output:(15, 20), (7, 24) Explanation: Both the pairs satisfy the necessary conditions. Approach: Check all possible values of A and B in the
6 min read
Pythagorean Triplet in an array
Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2. Example:  Input: arr[] = {3, 1, 4, 6, 5} Output: True There is a Pythagorean triplet (3, 4, 5). Input: arr[] = {10, 4, 6, 12, 5} Output: False There is no Pythagorean triplet.  Recommended PracticePythagorean TripletTry It!Met
15+ min read
Pythagorean Triplet with given sum
A Pythagorean Triplet is a set of natural numbers such that a < b < c, for which a^2 + b^2 = c^2. For example, 3^2 + 4^2 = 5^2.Given a number n, find a Pythagorean Triplet with sum as given n. Examples : Input : n = 12Output : 3, 4, 5Note that 3, 4 and 5 is a Pythagorean Triplet with sum equal to 12. Input : n = 4.Output : No TripletThere doe
5 min read
Pythagorean Triplet with given sum using single loop
A Pythagorean Triplet is a set of natural numbers such that a < b < c, for which [Tex]a^2 + b^2 = c^2[/Tex] Given a number N, find a Pythagorean Triplet with sum given as N or return -1. Examples: Input: 12 Output: 3 4 5Explanation:32 + 42 = 52Input: 82Output: -1Approach: The idea is to find the value of b and c in terms of a and iterate a fr
6 min read
POTD Solutions | 3 Nov’ 23 | Pythagorean Triplet
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Hashing but will also help you build up problem-solving skills. POTD 3 November: Pythagorean TripletGiven
8 min read
Count triplets such that product of two numbers added with third number is N
Given a positive integer N, the task is to find the number of triplets (A, B, C) where A, B, C are positive integers such that the product of two numbers added with the third number is N i.e., A * B + C = N. Examples: Input: N = 3Output: 3Explanation:Following are the possible triplets satisfying the given criteria: (1, 1, 2): The value of 1*1 + 2
7 min read
Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15};Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} an
11 min read
Print all triplets in sorted array that form AP
Given a sorted array of distinct positive integers, print all triplets that form AP (or Arithmetic Progression) Examples : Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 }; Output : 6 9 12 2 12 22 12 17 22 2 17 32 12 22 32 9 22 35 2 22 42 22 32 42 Input : arr[] = { 3, 5, 6, 7, 8, 10, 12}; Output : 3 5 7 5 6 7 6 7 8 6 8 10 8 10 12 A simple so
12 min read
Sum of special triplets having elements from 3 arrays
Given three arrays A, B, and C, the task is to find sum of values of all special triplets. A special triplet is defined as a triplet (X, Y, Z) where the condition : X ? Y and Z ? Y always hold true. The value of each triplet (X, Y, Z) is given by: f(X, Y, Z) = (X + Y) * (Y + Z) Note: If a triplet is not 'special', f(x, y, z) = 0 for that particular
15+ min read
Triplets in array with absolute difference less than k
Given an array A[] of n elements and an integer k. The task is to find the number of triplet (x, y, z), where 0 <= x, y, z < n and x, y, z are the index in the array A[] such that: |A[x] - A[y]| <= k |A[y] - A[z]| <= k |A[z] - A[x]| <= k Examples: Input : A[] = { 1, 1, 2, 2, 3 }, k = 1 Output : 5 (0, 1, 2), (0, 1, 3), (0, 2, 3), (1,
8 min read
Count number of triplets with product equal to given number with duplicates allowed | Set-2
Given an array of positive integers(may contain duplicates) and a number ‘m’, find the number of unordered triplets ((Ai, Aj, Ak) and (Aj, Ai, Ak) and other permutations are counted as one only) with product equal to ‘m’. Examples: Input: arr[] = { 1, 4, 6, 2, 3, 8}, M = 24 Output: 3 The triplets are {1, 4, 6} {1, 3, 8} {4, 2, 3} Input: arr[] = { 0
14 min read
Maximum value of XOR among all triplets of an array
Given an array of integers 'arr', the task is to find the maximum XOR value of any triplet pair among all the possible triplet pairs. Note: An array element can be used more than once. Examples: Input: arr[] = {3, 4, 5, 6} Output: 7 The triplet with maximum XOR value is {4, 5, 6}. Input: arr[] = {1, 3, 8, 15} Output: 15 Approach: Store all possible
5 min read
Count number of triplets with product equal to given number | Set 2
Given an array of distinct integers(considering only positive numbers) and a number ‘m’, find the number of triplets with the product equal to ‘m’. Examples: Input: arr[] = { 1, 4, 6, 2, 3, 8} m = 24 Output: 3 Input: arr[] = { 0, 4, 6, 2, 3, 8} m = 18 Output: 0 An approach with O(n) extra space has already been discussed in previous post. In this p
7 min read
Count number of triplets with product equal to given number with duplicates allowed
Given an array of positive integers (may contain duplicates), the task is to find the number of triplets whose product is equal to a given number t. Examples: Input: arr = [1, 31, 3, 1, 93, 3, 31, 1, 93] t = 93 Output: 18 Input: arr = [4, 2, 4, 2, 3, 1] t = 8 Output: 4 [(4, 2, 1), (4, 2, 1), (2, 4, 1), (4, 2, 1)] Naive Approach: The easiest way to
15+ min read
Find triplets in an array whose AND is maximum
Given an array of positive integers of size n. Find the count of the triplets whose AND is maximum and also find that maximum given that i < j < k where i, j, k are the indices of the numbers. Assuming that numbers will not be greater than 10^9. Examples: Input : a[] = {1, 2, 3, 4, 5, 6} Output : 1 4 Explanation: Maximum number that can forme
11 min read
Count triplets in a sorted doubly linked list whose product is equal to a given value x
Given a sorted doubly linked list of distinct nodes(no two nodes have the same data) and a value x. The task is to count the triplets in the list that product up to a given value x. Examples: Input: list = 1->2->4->5->6->8->9, x = 8 Output: 1 Triplet is (1, 2, 4) Input: list = 1->2->4->5->6->8->9, x = 120 Output:
15+ min read
Count triplets (a, b, c) such that a + b, b + c and a + c are all divisible by K
Given two integers 'N' and 'K', the task is to count the number of triplets (a, b, c) of positive integers not greater than 'N' such that 'a + b', 'b + c', and 'c + a' are all multiples of 'K'. Note that 'a', 'b' and 'c' may or may not be the same in a triplet. Examples: Input: N = 2, K = 2 Output: 2Explanation: All possible triplets are (1, 1, 1)
5 min read
Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
Given an integer X and a binary tree, the task is to count the number of triplet triplets of nodes such that their sum is greater than X and they have a grandparent -> parent -> child relationship. Example: Input: X = 100 10 / \ 1 22 / \ / \ 35 4 15 67 / \ / \ / \ / \ 57 38 9 10 110 312 131 414 / \ 8 39 Output: 6 The triplets are: 22 -> 15
15+ min read
Count of ordered triplets with indices (i, j, k) representing distinct values and j - i != k - j
Given a ternary string S consisting of only three characters, the task is to find the count of ordered triplets (i, j, k) such that S[i], S[j] and S[k] are distinct and j - i != k - j. Example: Input: str = "AABC"Output: 1Explanation: Only the triplet (0, 2, 3) satisfies the required conditions as S[0], S[2], and S[3] are distinct and 2 - 0 != 3 -
8 min read
Find triplet such that number of nodes connecting these triplets is maximum
Given a Tree with N nodes, the task is to find a triplet of nodes (a, b, c) such that the number of nodes covered in the path connecting these nodes is maximum. (Count a node only once).Examples: Input: N = 4 Edge Set: 1 2 1 3 1 4 Output: (2, 3, 4) (2, 3, 4) as path between (2, 3) covers nodes 2, 1, 3 and path between (3, 4) covers nodes 3, 1, 4. H
13 min read
Count the triplets such that A[i] < B[j] < C[k]
Given three array A[], B[] and C[] of N integers each. The task is to find the count of triplets (A[i], B[j], C[k]) such that A[i] < B[j] < C[k]. Input: A[] = {1, 5}, B[] = {2, 4}, C[] = {3, 6} Output: 3 Triplets are (1, 2, 3), (1, 4, 6) and (1, 2, 6)Input: A[] = {1, 1, 1}, B[] = {2, 2, 2}, C[] = {3, 3, 3} Output: 27 Approach: Sort all the gi
11 min read
Number of triplets such that each value is less than N and each pair sum is a multiple of K
Given two integers N and K. Find the numbers of triplets (a, b, c) such that 0 ? a, b, c ? N and (a + b), (b + c) and (c + a) are multiples of K. Examples: Input: N = 3, K = 2 Output: 9 Triplets possible are: {(1, 1, 1), (1, 1, 3), (1, 3, 1) (1, 3, 3), (2, 2, 2), (3, 1, 1) (3, 1, 1), (3, 1, 3), (3, 3, 3)} Input: N = 5, K = 3 Output: 1 Only possible
5 min read
Count non-negative triplets with sum equal to N
Given an integer N. The task is to find the number of different ordered triplets(a, b, c) of non-negative integers such that a + b + c = N .Examples: Input : N = 2 Output : 6 Triplets are : (0, 0, 2), (1, 0, 1), (0, 1, 1), (2, 0, 0), (0, 2, 0), (1, 1, 0)Input : N = 50 Output : 1326 Naive Approach: We can use three nested loops to generate all possi
5 min read
Find number of triplets in array such that a[i]>a[j]>a[k] and i<j<k
Given an array arr of size N. The task is to count the number of triplets in the array such that a[i]>a[j]>a[k] and i<j<k Examples: Input : arr[] = {10, 8, 3, 1} Output : 4 The triplets are: 1, 3, 8 1, 3, 10 1, 8, 10 3, 8, 10 Input : arr[] = {88, 64, 45, 21, 54} Output : 5 Prerequisites: Count inversions Approach: Find the greater_left
12 min read
Count of triplets that satisfy the given equation
Given an array arr[] of N non-negative integers. The task is to count the number of triplets (i, j, k) where 0 ? i < j ? k < N such that A[i] ^ A[i + 1] ^ ... ^ A[j - 1] = A[j] ^ A[j + 1] ^ ... ^ A[k] where ^ is the bitwise XOR.Examples: Input: arr[] = {2, 5, 6, 4, 2} Output: 2 The valid triplets are (2, 3, 4) and (2, 4, 4).Input: arr[] = {5,
5 min read
Count of triplets in an array that satisfy the given conditions
Given an array arr[] of N elements, the task is to find the count of triplets (arr[i], arr[j], arr[k]) such that (arr[i] + arr[j] + arr[k] = L) and (L % arr[i] = L % arr[j] = L % arr[k] = 0.Examples: Input: arr[] = {2, 4, 5, 6, 7} Output: 1 Only possible triplet is {2, 4, 6}Input: arr[] = {4, 4, 4, 4, 4} Output: 10 Approach: Consider the equations
13 min read
Article Tags :
Practice Tags :