Project Euler problem 9. 私はそれを解こうとしましたが、実際には、ピタゴラスのトリプレットではないトリプレットが得られ、それらの合計は 1000 です。なぜですか? 私はそれらがピタゴラスの三つ子であることを確認しました。これが私の長くて最適化されていないコードです:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a,b,c; //Decalring the triplets...
a=1; //First triplet starts with 3
b=1;
int c2;//c square
while(true)
{
for(b=1;b<a;b++){
c2 = a*a+b*b;
c = sqrt(c2);
if(c*c == c2 && a+b+c==1000)
{
cout<<a<<","<<b<<","<<c<<"\n";
}
a++;
}
b++;
}
}
最終的な作業コード:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x,y,z,a;
for(x=1;x<=1000;x++)
{
for(y=1;y<=1000;y++)
{
a = x*x+y*y;
z=sqrt(a);
if(z*z==a && x+y+z==1000 && x<y){
cout<<x<<","<<y<<","<<z<<"."<<"\n";
cout<<"So the product of all of the three triplets is "<<x*y*z;
}
}
}
return 0;
}