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.
Input : n = 12 Output : 3, 4, 5 Note that 3, 4 and 5 is a Pythagorean Triplet with sum equal to 12. Input : n = 4. Output : No Triplet There does not exist a Pythagorean Triplet with sum equal to 4.
A simple solution is to run three nested loops to generate all possible triplets and for every triplet, check if it is a Pythagorean Triplet and has given sum. Time complexity of this solution is O(n3).
An efficient solution is to run two loops, where first loop runs from i = 1 to n/3, second loop runs from j = i+1 to n/2. In second loop, we check if (n – i – j) is equal to i * i + j * j.
3, 4, 5
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Pythagorean Triplet with given sum using single loop
- Possible pairs forming a Pythagorean Triple with a given value
- Generate Pythagorean Triplets
- Check if a number is a Pythagorean Prime or not
- Twin Pythagorean triplets in an array
- Find a triplet in an array whose sum is closest to a given number
- Minimum possible sum of prices of a Triplet from the given Array
- Sum of multiplication of triplet of divisors of a number
- Triplet with no element divisible by 3 and sum N
- Puzzle | Place numbers 1 to 9 in a Circle such that sum of every triplet in straight line is 15
- Count triplet pairs (A, B, C) of points in 2-D space that satisfy the given condition
- Find distinct integers for a triplet with given product
- Largest lexicographic triplet from a given Array that forms a triangle
- Generate a pythagoras triplet from a single integer
- Prime Triplet
- Finding a Non Transitive Coprime Triplet in a Range
- Count triplet of indices (i, j, k) such that XOR of elements between [i, j) equals [j, k]
- Maximum value of expression (arr[i] + arr[j] * arr[k]) formed from a valid Triplet
- Check if every vertex triplet in graph contains two vertices connected to third vertex
- Count of numbers satisfying m + sum(m) + sum(sum(m)) = N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : vt_m