Generate Pythagorean Triplets - GeeksforGeeks
A Pythagorean triplet is a set of three integers a, b and c such that a2 + b2 = c2.
Given a limit, generate all positive Pythagorean triplets such that all values in triplets are smaller than given limit.
Related: Find Pythagorean triples in an unsorted array
Read full article from Generate Pythagorean Triplets - GeeksforGeeks
A Pythagorean triplet is a set of three integers a, b and c such that a2 + b2 = c2.
Given a limit, generate all positive Pythagorean triplets such that all values in triplets are smaller than given limit.
Input: limit = 10 Output: 3 4 -> 5 8 6 -> 10
A Simple Solution is to run generate all triplets smaller than given limit using three nested loop. For every triplet, check if Pythagorean condition is true, if true, then print the triplet. Time complexity of this solution is O(limit3).
An Efficient Solution can print all triplets in O(limit2) time. The idea is to observe use square sum relation of Pythagorean triplet, i.t., addition of squares of a and b is equal to square of c, we can write these number in terms of m and n such that,
a = m2 - n2 b = 2 * m * n c = m2 + n2 because, a2 = m^4 + n^4 – 2 * m2 * n2 b 2 = 4 * m2 * n2 c2 = m^4 + n^4 + 2* m2 * n2
by above we can see that a2 + b2 = c2
so instead of iterating for a, b and c we can iterate for m and n and can generate these triplets and as we are iterating for m and n only
above algorithm will generate Pythagorean triplets in O(limit2) time complexity.
so instead of iterating for a, b and c we can iterate for m and n and can generate these triplets and as we are iterating for m and n only
above algorithm will generate Pythagorean triplets in O(limit2) time complexity.
void
pythagoreanTriplets(
int
limit)
{
// triplet: a^2 + b^2 = c^2
int
a, b, c=0;
// loop from 2 to max_limitit
int
m = 2;
// Limiting c would limit all a, b and c
while
(c < limit)
{
// now loop on j from 1 to i-1
for
(
int
n = 1; n < m; ++n)
{
// Evaluate and print triplets using
// the relation between a, b and c
a = m*m - n*n;
b = 2*m*n;
c = m*m + n*n;
if
(c > limit)
break
;
printf
(
"%d %d %d\n"
, a, b, c);
}
m++;
}
}
Read full article from Generate Pythagorean Triplets - GeeksforGeeks