Find Pythagorean Triplet with given sum using Mathematical Formula
Last Updated :
15 Oct, 2024
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]));
Related Articles:
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read