garryhtreez

5.20

Nov 15th, 2020 (edited)
510
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. /* 5.20 Pythagorean Triples
  2.         Deitel & Deitel C++ How to Program, 10th ed (Indian subcontinent adaptation)
  3.     Visual Studio Community 2019 */
  4.  
  5. #include <iostream>
  6. #include <iomanip>
  7. using namespace std;
  8.  
  9. int main(void) {
  10.     int count{ 0 };
  11.     int a{ 1 }, b{ 1 }, h{ 1 };
  12.     int aSq{ 1 }, bSq{ 1 }, hSq{ 1 };
  13.     // heading
  14.     cout << "side1  (squared)  side2  (squared)  Sum of squares  hypotenuse  hypotenuse squared\n\n";
  15.     while (h < 501 && a < 501 && b < 501) {
  16.         for (a = 1; a < 500; a++) {
  17.             for (b = 1; b < 500; b++) {
  18.                 for (h = 1; h < 501; h++) {
  19.                     aSq = a * a;
  20.                     bSq = b * b;
  21.                     hSq = h * h;
  22.                     if (aSq + bSq == hSq) {
  23.                         cout << setw(4) << a << setw(9) << aSq << setw(9) << b
  24.                             << setw(9) << bSq << setw(12) << aSq + bSq << setw(12)
  25.                             << h << setw(18) << hSq << "\n";
  26.                         count++;
  27.                     }
  28.                 }
  29.             }
  30.         }
  31.     }
  32.     // Values for side1 and side2 eventually get swapped resulting in twice the number of
  33.     // triples. To get unique triples divide total by 2.
  34.     cout << "\nBefore 501 was reached, found " << count/2 << " unique pythagorean triples.\n\n";
  35.     return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment