The Pythagorean formula is a 2 +b 2 =c 2 where a and b are the lengths of the \"
ID: 3640973 • Letter: T
Question
The Pythagorean formula is a2+b2=c2 where a and b are the lengths of the "legs" (shorter sides) of a right triangle and c is the length of the hypotenuse (longest side) of the same right triangle. The numbers a, b and c are called a Pythagorean triple.
There are combinations of integers which are Pythagorean triples like 3, 4 and 5: 32+42=52. You goal is write a program to print integer Pythagorean triples.
Your program should first prompt for and read a number n which will be maximum value for c. Then it should test each value of c in a loop to see if there are any integers a and b which work with c to form a Pythagorean triple. If so, then the values for a, b and c should be printed.
Suppose the number entered for maximum c is 20. The program will output
3 4 5
6 8 10
5 12 13
9 12 15
8 15 17
12 16 20
It should be clear that there will be an outer loop incrementing c from 1 to n. Then inside this loop the program needs to try all values of a from 1 to c-1. For each value of a there is only 1 reasonable value of b to try: sqrt(c*c-a*a). This value for b needs to be tested to see if a*a+b*b == c*c. If the test passes the triple should be printed and it is time to break out of the inner loop.
After reading n use an assert statement to verify that n is greater than 0 and less than or equal to 1000.
Explanation / Answer
#include <iostream>
#include <math.h>
using namespace std;
//PROTOTYPES
void getMaxC(int &n);
void printPythagoreanTriples(int n);
int main()
{
//LOCAL DECLARATIONS
int n;
getMaxC(n);
printPythagoreanTriples(n);
cin.sync();
cin.get();
return 0;
}
//---------------------------------------------------------
// FUNCTION DEFINITIONS
//---------------------------------------------------------
void getMaxC(int &n)
{
n = 0;
while (n < 1 || n > 1000)
{
cout << "Enter maximum c: ";
cin >> n;
if (n < 1 || n > 1000)
cout << "Maximum c must be greater than 0 and less than or equal to 1000 ";
}
}
//---------------------------------------------------------
void printPythagoreanTriples(int n)
{
for (int c = 1; c <= n; c++)
{
for (int a = 1; a < c; a++)
{
int b = sqrt((double) c * c - a * a);
if (a * a + b * b == c * c)
{
cout << a << " " << b << " " << c << endl;
break;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.