C++ program to check the 3 numbers are pythagorean triples
Answers
Answer:
try to run it.
Explanation:
// A C++ program that returns true if there is a Pythagorean
// Triplet in a given array.
#include <iostream>
using namespace std;
// Returns true if there is Pythagorean triplet in ar[0..n-1]
bool isTriplet(int ar[], int n)
{
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
// Calculate square of array elements
int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k];
if (x == y + z || y == x + z || z == x + y)
return true;
}
}
}
// If we reach here, no triplet found
return false;
}
/* Driver program to test above function */
int main()
{
int ar[] = { 3, 1, 4, 6, 5 };
int ar_size = sizeof(ar) / sizeof(ar[0]);
isTriplet(ar, ar_size) ? cout << "Yes" : cout << "No";
return 0;
}
Answer:
Explanation:
// C++ program to generate pythagorean
// triplets smaller than a given limit
#include <bits/stdc++.h>
// Function to generate pythagorean
// triplets smaller than limit
void pythagoreanTriplets(int limit)
{
// triplet: a^2 + b^2 = c^2
int a, b, c = 0;
// loop from 2 to max_limitit
int m = 2;
// Limiting c would limit
// all a, b and c
while (c < limit) {
// now loop on j from 1 to i-1
for (int n = 1; n < m; ++n) {
// Evaluate and print triplets using
// the relation between a, b and c
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
if (c > limit)
break;
printf("%d %d %d\n", a, b, c);
}
m++;
}
}
// Driver Code
int main()
{
int limit = 20;
pythagoreanTriplets(limit);
return 0;
}