In: Computer Science
/*
A right-angle triangle with integer sides a, b, c, such as 3, 4, 5,
is called a Pythagorean triple. The condition is that hypotenuse to
power of 2 is equal to adding of square of the 2 other sides. In
this example 25 = 16 + 9. Use brute force approach to find all the
triples such that no side is bigger than 50.
For this you should first implement the following Triangle class
and its methods. Then use it in main() to find all pythagorean
triples and put then in a std::vector. Finally print them out as
triples, like
(3, 4, 5)
.....
Make sure your output contains a triple only once, and not any
reordered ones, this means (3, 4, 5) is the same as (4, 3, 5) and
so only the increasing order triple should be printed out. This
means only (3, 4, 5) shoud be printed.
You program should print out all possible pythogorean triples with
sides <= 50.
*/
class Triangle
{
public:
Triangle(int a, int b, int c) // constructor.
Implement this
{}
bool isPythagorean() const // implement this
properly
{
return false;
}
private: // what do you put in private section?
}
int main()
{
}
#include<iostream>
#include<vector>
#include<tuple>
using namespace std;
class Triangle
{
/* private section of class has three sides of triangle*/
int side1;
int side2;
int side3;
public:
/* parametrized constructor to initialize sides of triangle*/
Triangle(int a, int b, int c)
{
side1 = a;
side2 = b;
side3 = c;
}
/* function to check if three sides are forming pythagorean triplet or not*/
bool isPythagorean() const
{
if ((side3 * side3) == ((side2 * side2) + (side1 * side1))) /* if side3^2 = side1^2 + side2^2 then it is a pythagorean triplet */
return true;
return false;
}
};
int main()
{
vector<tuple<int, int, int> > v; //declare vector v of tuples
for (int i = 1; i <= 50; i++) /* three loop to generate all the possible pairs of sides */
{
for (int j = i + 1; j <= 50; j++)
{
for (int k = j + 1; k <= 50; k++)
{
Triangle obj(i, j, k); /* create object of triangle class with three sides i,j,k*/
if (obj.isPythagorean()) /* check if three sides form right triangle, if yes add tuple to vector*/
{
v.push_back(make_tuple(i, j, k));
}
}
}
}
cout << "The Pythagorean triplets are :: " << endl;
for (int i = 0; i < v.size(); i++) /* print all the tuples on console */
{
cout << "(" << get<0>(v[i]) << "," << get<1>(v[i]) << "," << get<2>(v[i]) << ")"<<endl;
}
return 0;
}