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
- Generate Pythagorean Triplets
- Check if a number is a Pythagorean Prime or not
- Prime Triplet
- Triplet with no element divisible by 3 and sum N
- Sum of multiplication of triplet of divisors of a number
- Generate a pythagoras triplet from a single integer
- Finding a Non Transitive Coprime Triplet in a Range
- Find a triplet in an array whose sum is closest to a given number
- Count triplet pairs (A, B, C) of points in 2-D space that satisfy the given condition
- Maximum Sequence Length | Collatz Conjecture
- Count the number of subsequences of length k having equal LCM and HCF
- Minimum cost to make all array elements equal
- Check if a right-angled triangle can be formed by moving any one of the coordinates
- Sum of the digits of square of the given number which has only 1's as its digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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