C++ program to find Pythagorean triplets within given limit

In this tutorial, we will be working on finding the Pythagorean triplets under the given limit in C++. Here, the triplets will be found based on interesting math formulas.

Method:

The popular Pythagorean theorem discusses the relation between sides of a right-angled triangle. If you have three sides namely a, b, c,  then the “sum of squares of two sides equals the third side”. Equation: a2 + b= c². So with this square sum relation, we are now going to extract Pythagorean triplets.

In general, we calculate the Pythagorean triplets manually using theorem, and others. We are now going to see the method used for generating the Pythagorean triplets below the given range in C++.

Algorithm: Find Pythagorean triplets

We can represent the above equation in terms of p, q which gives

  • a = p² – q²
  • b = 2 * p * q
  • c = p² + q²

These are represented because,

  • a² = p⁴ + q⁴ – 2 * m² * n²
  • b² = 4 * m² * n²
  • c² = p⁴ + q⁴ + 2 * m² * n²

So, by using the above formulas, we reduced the no of iterations from 3 variables(a, b, c) to 2 variables(p, q).

C++ code to find Pythagorean triplets within given limit

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int l; // given limit
    cin>>l;
    int a, b, c = 0; 
    int p = 2;
    while (c < l) {
        for (int q = 1; q < p; ++q) {
            a = p * p - q * q;
            b = 2 * p * q;
            c = p * p + q * q;
            if (c > l)
                break;
 
            printf("%d %d %d\n", a, b, c);
        }
        p++;
    }
    return 0;
}

Input:

30

Output:

3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *