Open In App

Find Pythagorean Triplet with given sum

Last Updated : 15 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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.

[Naive Approach] - Using three nested loops - O(n^3) Time and O(1) Space

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.

C++
// C++ program to find Pythagorean triplets
// having given sum using three nested loops

#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> pythagoreanTriplet(int target) {
 	vector<vector<int>> res;   
 
    // Generating all possible triplets
    for(int a = 0; a < target - 2; a++) {
        for(int b = a + 1; b < target - 1; b++) {
            for(int c = b + 1; c < target; c++) {
                
                // If this triplet satisfies the condition 
              	// then, add it to the result
                if(a + b + c == target && a*a + b*b == c*c)
                    res.push_back({a, b, c});
            }
        }
    }
    
    return res;
}

int main() {
    int target = 60;
    vector<vector<int>> ans = pythagoreanTriplet(target);
    for(vector<int> triplet : ans)
        cout << triplet[0] << " " << triplet[1] << " " << 
      									triplet[2] << endl;
 	return 0;
}
C
// C program to find Pythagorean triplets 
// having given sum using three nested loops

#include <stdio.h>

#define MAX_SIZE 100

void pythagoreanTriplet(int triplets[][3], int *count, int target) {
    *count = 0;

    // Generating all possible triplets
    for (int a = 0; a < target - 2; a++) {
        for (int b = a + 1; b < target - 1; b++) {
            for (int c = b + 1; c < target; c++) {

                // If this triplet satisfies the condition
                // then, add it to the result
                if (a + b + c == target && a * a + b * b == c * c) {
                    triplets[*count][0] = a;
                    triplets[*count][1] = b;
                    triplets[*count][2] = c;
                    (*count)++;
                }
            }
        }
    }
}

int main() {
    int triplets[MAX_SIZE][3];
    int count;

    int target = 60;
    pythagoreanTriplet(triplets, &count, target);
    for (int i = 0; i < count; i++) 
        printf("%d %d %d\n", triplets[i][0], triplets[i][1], 
               									triplets[i][2]);

    return 0;
}
Java
// Java program to find Pythagorean triplets 
// having given sum using three nested loops

import java.util.ArrayList;
import java.util.List;

class GfG {
    static List<List<Integer>> pythagoreanTriplet(int target) {
        List<List<Integer>> res = new ArrayList<>();

        // Generating all possible triplets
        for (int a = 0; a < target - 2; a++) {
            for (int b = a + 1; b < target - 1; b++) {
                for (int c = b + 1; c < target; c++) {

                    // If this triplet satisfies the condition
                    // then, add it to the result
                    if (a + b + c == target && a * a + b * b == c * c) {
                        res.add(List.of(a, b, c));
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int target = 60;
        List<List<Integer>> ans = pythagoreanTriplet(target);
        for (List<Integer> triplet : ans) {
            System.out.println(triplet.get(0) + " " + triplet.get(1) + " " 
                               							+ triplet.get(2));
        }
    }
}
Python
# Python program to find Pythagorean triplets 
# having given sum using three nested loops

def pythagoreanTriplet(target):
    res = []

    # Generating all possible triplets
    for a in range(target - 2):
        for b in range(a + 1, target - 1):
            for c in range(b + 1, target):

                # If this triplet satisfies the condition
                # then, add it to the result
                if a + b + c == target and a * a + b * b == c * c:
                    res.append([a, b, c])

    return res

target = 60
ans = pythagoreanTriplet(target)
for triplet in ans:
    print(*triplet)
C#
// C# program to find Pythagorean triplets 
// having given sum using three nested loops

using System;
using System.Collections.Generic;

class GfG {
    static List<List<int>> PythagoreanTriplet(int target) {
        List<List<int>> res = new List<List<int>>();

        // Generating all possible triplets
        for (int a = 0; a < target - 2; a++) {
            for (int b = a + 1; b < target - 1; b++) {
                for (int c = b + 1; c < target; c++) {

                    // If this triplet satisfies the condition
                    // then, add it to the result
                    if (a + b + c == target && a * a + b * b == c * c) {
                        res.Add(new List<int> { a, b, c });
                    }
                }
            }
        }
        return res;
    }

    static void Main() {
        int target = 60;
        List<List<int>> ans = PythagoreanTriplet(target);
        foreach (var triplet in ans) {
            Console.WriteLine($"{triplet[0]} {triplet[1]} {triplet[2]}");
        }
    }
}
JavaScript
// JavaScript program to find Pythagorean triplets 
// having given sum using three nested loops

function pythagoreanTriplet(target) {
    const res = [];

    // Generating all possible triplets
    for (let a = 0; a < target - 2; a++) {
        for (let b = a + 1; b < target - 1; b++) {
            for (let c = b + 1; c < target; c++) {

                // If this triplet satisfies the condition
                // then, add it to the result
                if (a + b + c === target && a * a + b * b === c * c) {
                    res.push([a, b, c]);
                }
            }
        }
    }
    return res;
}

const target = 60;
const ans = pythagoreanTriplet(target);
ans.forEach(triplet => console.log(triplet.join(' ')));

Output
10 24 26
15 20 25

[Better Approach] - Using two nested loops - O(n^2) Time and O(1) Space

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.

C++
// C++ program to find Pythagorean triplets having
// given sum using two nested loops

#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> pythagoreanTriplet(int target) {
  	vector<vector<int>> res;  
  
    // Generating all possible pairs
    for(int a = 1; a < target - 2; a++) {
        for(int b = a + 1; b < target - 1; b++) {
            
            // Third value of triplet
            int c = target - a - b;
            
          	// c should be the maximum value of triplet
            if(c <= b)
                continue;
            
            // if {a, b, c} forms a pythagorean Triplet
            // then add it to the reuslt.
            if(a*a + b*b == c*c)
                res.push_back({a, b, c});
        }
    }
    
    return res;
}

int main() {
    int target = 60;
    vector<vector<int>> ans = pythagoreanTriplet(target);
    for(vector<int> triplet : ans)
        cout << triplet[0] << " " << triplet[1] << " " << 
      									triplet[2] << endl;
 	return 0;
}
C
// C program to find Pythagorean triplets 
// having given sum using two nested loops

#include <stdio.h>

#define MAX_SIZE 100

void pythagoreanTriplet(int triplets[][3], int *count, int target) {
    *count = 0;

    // Generating all possible pairs
    for (int a = 1; a < target - 2; a++) {
        for (int b = a + 1; b < target - 1; b++) {

            // Third value of triplet
            int c = target - a - b;

            // c should be the maximum value of triplet
            if (c <= b)
                continue;

            // If {a, b, c} forms a Pythagorean triplet
          	// then add it to the result
            if (a * a + b * b == c * c) {
                triplets[*count][0] = a;
                triplets[*count][1] = b;
                triplets[*count][2] = c;
                (*count)++;
            }
        }
    }
}

int main() {
    int triplets[MAX_SIZE][3];
    int count;

    int target = 60;
    pythagoreanTriplet(triplets, &count, target);
    for (int i = 0; i < count; i++) 
        printf("%d %d %d\n", triplets[i][0], triplets[i][1], triplets[i][2]);

    return 0;
}
Java
// Java program to find Pythagorean triplets having given sum
// using two nested loops

import java.util.ArrayList;
import java.util.List;

class GfG {
    static List<List<Integer>> pythagoreanTriplet(int target) {
        List<List<Integer>> res = new ArrayList<>();

        // Generating all possible pairs
        for (int a = 1; a < target - 2; a++) {
            for (int b = a + 1; b < target - 1; b++) {

                // Third value of the triplet
                int c = target - a - b;

                // c should be the maximum value of the triplet
                if (c <= b)
                    continue;

                // If {a, b, c} forms a Pythagorean triplet
              	// then add it to the result
                if (a * a + b * b == c * c)
                    res.add(List.of(a, b, c));
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int target = 60;
        List<List<Integer>> ans = pythagoreanTriplet(target);
        for (List<Integer> triplet : ans) {
            System.out.println(triplet.get(0) + " " + triplet.get(1)
                               				+ " " + triplet.get(2));
        }
    }
}
Python
# Python program to find Pythagorean triplets having 
# given sum using two nested loops

def pythagoreanTriplet(target):
    res = []

    # Generating all possible pairs
    for a in range(1, target - 2):
        for b in range(a + 1, target - 1):

            # Third value of the triplet
            c = target - a - b

            # c should be the maximum value of the triplet
            if c <= b:
                continue

            # If {a, b, c} forms a Pythagorean triplet
            # then, add it to the result
            if a * a + b * b == c * c:
                res.append([a, b, c])

    return res

target = 60
ans = pythagoreanTriplet(target)
for triplet in ans:
    print(*triplet)
C#
// C# program to find Pythagorean triplets having given 
// sum using two nested loops

using System;
using System.Collections.Generic;

class GfG {
    static List<List<int>> PythagoreanTriplet(int target) {
        List<List<int>> res = new List<List<int>>();

        // Generating all possible pairs
        for (int a = 1; a < target - 2; a++) {
            for (int b = a + 1; b < target - 1; b++) {

                // Third value of triplet
                int c = target - a - b;

                // c should be the maximum value of triplet
                if (c <= b)
                    continue;

                // If {a, b, c} forms a Pythagorean triplet
              	// then, add it to the result
                if (a * a + b * b == c * c)
                    res.Add(new List<int> { a, b, c });
            }
        }
        return res;
    }

    static void Main() {
        int target = 60;
        List<List<int>> ans = PythagoreanTriplet(target);
        foreach (var triplet in ans) {
            Console.WriteLine($"{triplet[0]} {triplet[1]} {triplet[2]}");
        }
    }
}
JavaScript
// JavaScript program to find Pythagorean triplets 
// having given sum using two nested loops

function pythagoreanTriplet(target) {
    const res = [];

    // Generating all possible pairs
    for (let a = 1; a < target - 2; a++) {
        for (let b = a + 1; b < target - 1; b++) {

            // Third value of triplet
            let c = target - a - b;

            // It should be the maximum value of triplet
            if (c <= b) continue;

            // If {a, b, c} forms a Pythagorean triplet
            // then, add it to the result
            if (a * a + b * b === c * c) {
                res.push([a, b, c]);
            }
        }
    }
    return res;
}

const target = 60;
const ans = pythagoreanTriplet(target);
ans.forEach(triplet => console.log(triplet.join(' ')));

Output
10 24 26
15 20 25

[Expected Approach] - 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, 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.



Next Article
Practice Tags :

Similar Reads