C++

Generating Pythagorean Triples

Pythagorean_Triples

A pythagorean triple is a set of three positive integers A, B and C such that the equation C2 = A2 + B2 always holds true.

Properties of Pythagorean triple

  • If A, B and C form a pythagorean triple, then A < B < C holds true.
  • It always has two odd numbers and one even number or all even numbers.
  • If the smallest number in the pythagorean triple is even, say A, then the other 2 odd numbers would be (A/2)2-1 and (A/2)2+1.
    Example 1: (8, ((8/2)2-1), ((8/2)2+1)) i.e (8, 15, 17)
    Example 2: (12, ((12/2)2-1), ((12/2)2+1)) i.e (12, 35, 36)
  • If the smallest numberin the pythagorean triple is odd, say A, then the other 2 numbers would be (A2)/2 and (A2)/2+1.
    Example 1: (9, (92)/2, (92)/2+1) i.e (9, 40, 41)
    Example 2: (3, (32)/2, (32)/2+1) i.e (3, 4, 5)







Program for generating Pythagorean triples.

#include<iostream>
using namespace std;

// Finding pythagorean triple where the biggest number is <= upto
void Get_Pythagorean_Triples (int upto) {

     // If (a, b, c) form a pythagorean triple, then (a < b < c) must hold.
     // Thus a has to be less than b, b should be greater than a and 
     // less than c.
     
     int a, b, c;

     for (c = upto; c >= 1; c--) {
         a = 1;     // a starts from the 1st number.
         b = c - 1; // b starts from the 2nd-last number.
         while (a < b) { // a has to be smaller than b.
             if (a*a + b*b == c*c) {
                 cout << a << " " << b << " " << c << endl;
                 a++;
                 b--;
             } else if ( a*a + b*b < c*c) {
                 a++;
             } else {
                 b--;
             }
         }
     }
}

int main() {
    int upto = 100;
    Get_Pythagorean_Triples(upto);
    return 0;
}

Output

28 96 100
60 80 100
65 72 97
57 76 95
35 84 91
54 72 90
39 80 89
60 63 87
13 84 85
36 77 85
40 75 85
51 68 85
18 80 82
48 64 80
30 72 78
21 72 75
45 60 75
24 70 74
48 55 73
42 56 70
32 60 68
16 63 65
25 60 65
33 56 65
39 52 65
11 60 61
36 48 60
40 42 58
33 44 55
28 45 53
20 48 52
24 45 51
14 48 50
30 40 50
27 36 45
9 40 41
24 32 40
15 36 39
12 35 37
21 28 35
16 30 34
18 24 30
20 21 29
10 24 26
7 24 25
15 20 25
12 16 20
8 15 17
9 12 15
5 12 13
6 8 10
3 4 5



Copyright (c) 2019-2022, Algotree.org.
All rights reserved.