I was writing some code to calculate Pythagorean triples, but then I got some values which were not solutions. Here is the code:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int j, counter = 0;
double candidate, sqrnbr;
for (int i = 400; i <= 500; i++) //note that the range is only from 400-500 since I am still testing the code
{
for (j = i; j <= 500; j++)
{
candidate = i*i+j*j;
sqrnbr=sqrt(candidate);
if (candidate/sqrnbr==sqrnbr)
{
cout << i << " and " << j << " and " << sqrnbr << endl;
counter++;
}
}
}
cout << counter << endl;
system("pause");
return 0;
}
One of the outputs it gave was 408, 410 and 578.415. Does anyone know why this happens?
You calculate a
doubleand never check whether it’s an integer value, so you getdoublevalues. You don’t get a lot more because the square root is generally not representable as adouble, sois false for many values of
candidate.To generate Pythagorean triplets, use only integer arithmetic. And there are better methods than brute force, there’s a classic formula, all Pythagorean triplets are of the form
for some
d, m, n.