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 + b2 = 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
The below code has been updated as it had minor issues in the previous version.
#include <iostream> using namespace std; bool isPythagoreanTriplet(int a, int b, int c) { return (a * a + b * b == c * c); } void printPythagoreanTriplets(int limit) { for (int a = 1; a <= limit; a++) { for (int b = a + 1; b <= limit; b++) { for (int c = b + 1; c <= limit; c++) { if (isPythagoreanTriplet(a, b, c)) { cout << "(" << a << ", " << b << ", " << c << ")" << endl; } } } } } // Driver program to test the above function int main() { int limit = 20; cout << "Pythagorean triplets within the given limit are:"<< endl; printPythagoreanTriplets(limit); 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!
where are
9 12 15
15 20 25 ??
Please correct this code.