C++

Finding Pythagorean Triples



Program for finding all pythagorean triples in an array.

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>

using namespace std;

int main() {

    vector<int> vec = { 25, 3, 5, 4, 7, 9, 12, 13, 6, 8, 10, 15, 16, 20 };
    cout << "Array : ";
    for (const auto& val : vec) {
        cout << val << " ";
    } cout << endl;

    sort(vec.begin(), vec.end());

    for (int i=0; i<vec.size(); i++) {
        vec[i] = vec[i] * vec[i];
    }

    // Check for the condition (c = a + b)
    int a, b, c;
    for (c = vec.size(); c > 1; c--) {
        a = 0; // Start a from the beginning and keep incrementing, till it is less than b.
        b = c-1; // Start b from the second last position and keep decrementing till it is > a. 
        while (a < b) {
            if (vec[a] + vec[b] == vec[c]) {
                cout << "Found : " << sqrt(vec[a]) << " " << sqrt(vec[b]) << " " << sqrt(vec[c]) << endl;
                a++;
                b--;
            } else if (vec[a] + vec[b] < vec[c]) {
                a++;
            } else {
                b--;
            }
        }
    }
    return 0;
}

Output

Array : 25 3 5 4 7 9 12 13 6 8 10 15 16 20 
Found : 15 20 25
Found : 12 16 20
Found : 9 12 15
Found : 5 12 13
Found : 6 8 10
Found : 3 4 5


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