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
- Find a triplet in an array whose sum is closest to a given number
- Finding a Non Transitive Coprime Triplet in a Range
- Generate a pythagoras triplet from a single integer
- Count triplet pairs (A, B, C) of points in 2-D space that satisfy the given condition
- Number of ways to divide string in sub-strings such to make them in lexicographically increasing sequence
- Calculate the number of set bits for every number from 0 to N
- Number of ways to distribute N Paper Set among M students
- Diameter of a Binary Indexed Tree with N nodes
- Program for nth Fuss–Catalan Number
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