Open In App

Find Pythagorean Triplet with given sum using Mathematical Formula

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.

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.

C++
// C++ program to find Pythagorean triplets having given sum
// using mathematical formula

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

vector<vector<int>> pythagoreanTriplet(int target) {
    vector<vector<int>> res;

    // Iterating over all possible values of a
    for (int a = 1; a < target - 2; a++) {

        // Numerator and denominator for the value of c
        int num = 2 * a * a + target * target - 2 * target * a;
        int den = 2 * (target - a);

        // if the denominator is zero or it doesn't divide the
        // numerator completely then it won't give a valid c
        if (den == 0 || num % den != 0)
            continue;

        // Calculate 'c' and 'b' using derived equations
        int c = num / den;
        int b = target - a - c;

        // Ensure 'b' > 'a' to maintain valid order
        if (b > a)
            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 
// mathematical Formula

#include <stdio.h>

#define MAX_SIZE 100  

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

    // Iterating over all possible values of 'a'
    for (int a = 1; a < target - 2; a++) {

        // Numerator and denominator for the value of 'c'
        int num = 2 * a * a + target * target - 2 * target * a;
        int denom = 2 * (target - a);

        // if the denominator is zero or it doesn't divide 
        // the numerator completely then it won't give a valid c
        if (denom == 0 || num % denom != 0)
            continue;

        // Calculate 'c' and 'b' using derived equations
        int c = num / denom;
        int b = target - a - c;

        // Ensure 'b' > 'a' to maintain valid order
        if (b > a) {
            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 mathematical formula

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

class GfG {

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

        // Iterating over all possible values of 'a'
        for (int a = 1; a < target - 2; a++) {

            // Numerator and denominator for the value of 'c'
            int num = 2 * a * a + target * target - 2 * target * a;
            int denom = 2 * (target - a);

            // if the denominator is zero or it doesn't divide 
        	// the numerator completely then it won't give a valid c
            if (denom == 0 || num % denom != 0)
                continue;

            // Calculate 'c' and 'b' using derived equations
            int c = num / denom;
            int b = target - a - c;

            // Ensure 'b' > 'a' to maintain valid order
            if (b > a) 
                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 mathematical formula

def pythagoreanTriplet(target):
    res = []

    # Iterating over all possible values of 'a'
    for a in range(1, target - 2):
        
        # Numerator and denominator for the value of 'c'
        num = 2 * a**2 + target**2 - 2 * target * a
        denom = 2 * (target - a)

        # if the denominator is zero or it doesn't divide
        # the numerator completely then it won't give a valid c
        if denom == 0 or num % denom != 0:
            continue

        # Calculate 'c' and 'b' using derived equations
        c = num // denom
        b = target - a - c

        # Ensure 'b' is greater than 'a' to maintain valid order
        if b > a:
            res.append((a, b, c))

    return res

if __name__ == "__main__":
    target = 60
    ans = pythagoreanTriplet(target)

    # Print the retrieved triplets
    for triplet in ans:
        print(triplet[0], triplet[1], triplet[2])
C#
// C# program to find Pythagorean triplets having given sum 
// using mathematical formula

using System;
using System.Collections.Generic;

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

        // Iterating over all possible values of 'a'
        for (int a = 1; a < target - 2; a++) {

            // Numerator and denominator for the value of 'c'
            int num = 2 * a * a + target * target - 2 * target * a;
            int denom = 2 * (target - a);

            // if the denominator is zero or it doesn't divide
        	// the numerator completely then it won't give a valid c
            if (denom == 0 || num % denom != 0)
                continue;

            // Calculate 'c' and 'b' using derived equations
            int c = num / denom;
            int b = target - a - c;

            // Ensure 'b' > 'a' to maintain valid order
            if (b > a)
                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 mathematical formula

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

    // Iterating over all possible values of 'a'
    for (let a = 1; a < target - 2; a++) {

        // Numerator and denominator for the value of 'c'
        const num = 2 * a * a + target * target - 2 * target * a;
        const denom = 2 * (target - a);

        // if the denominator is zero or it doesn't divide 
        // the numerator completely then it won't give a valid c
        if (denom === 0 || num % denom !== 0)
            continue;

        // Calculate 'c' and 'b' using derived equations
        const c = num / denom;
        const b = target - a - c;

        // Ensure 'b' > 'a' to maintain valid order
        if (b > a)
            res.push([a, b, c]);
    }

    return res;
}

const target = 60;
const ans = pythagoreanTriplet(target);
ans.forEach(triplet => console.log(triplet[0], triplet[1], triplet[2]));

Output
10 24 26
15 20 25

Related Articles:


Next Article

Similar Reads