▼页尾

[Project Euler] Problem 9

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

寻找和为1000毕达哥拉斯三元数组,求它们的积

由于a < b < c,我们容易得到a的范围

a < 1000/(1+1+1.414); 估算有 a < 300;

#include <iostream>
using namespace std;

int main(){
for(int a=1; a<300; a++){
for(int b=(1000-a)/2; b>a; b--){
if(a*a+b*b == (1000-a-b)*(1000-a-b)){
cout
<< a*b*(1000-a-b) << endl;
return 0;
}
}
}
return 0;
}

事实上,我们不能确认这样的数只有一组,所以中间那个 “return 0;”应该去掉

posted @ 2011-02-22 20:32  xiatwhu  阅读(207)  评论(0编辑  收藏  举报
▲页首
西