【发布时间】:2013-04-19 11:40:18
【问题描述】:
Project Euler 问题 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;
}
【问题讨论】:
-
您不应该检查
sqrt(c2)是否完整吗? -
我做了,然后它没有给我任何结果......:/
标签: c++ pythagorean