[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.

 

我的解题思路是:

1. 理解题意:三个条件: 1)a2 + b2 = c2;2) a<b<c;3)a + b + c = 1000.

2. 思路:首先,由于a+b+c<1000,所以,三个数都是1000内的,马上想到可以用循环找出那个唯一满足条件的abc组合。首先从a开始for,它的取值范围是[1, 1000);b的for,取值范围是[a+1, 1000);对于一个ab组合,算出sqrt(a2 + b2),如果结果值符合:是整数 && a+b+c == 1000 && b < c,就是这个唯一数了。

看了Project Euler上其他人的解答后,改进算法如下:

1. 对于ab取值范围的缩小优化。a+b+c < 1000 && a<b<c==> 3a < 1000; b+c<1000 -> 2b<1000 ==> a的取值范围[1, 333)和b的取值范围[a+1, 500)。

2. 对于c,绝对是不需要再加一层循环的。 我的没错。改进的原因在于:1000-a-b得到一个候选c更直观更好理解。从速度上来说,和我的反向思路没区别。我的思路是判断满足了

a2 + b2的c是否满足a+b+c == 1000;而别人的思路是判断满足了a+b+c == 1000的c是否满足a2 + b2 = c2 
View Code
 1 #include <math.h>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 int _tmain(int argc, _TCHAR* argv[])
 6 {
 7     int a = 0;
 8     int b = 0;
 9     int c = 0;
10 
11     for(a = 1; a < 333; a++// a
12     {
13         for(b = a+1; b < 500; b++// b
14         {
15             c = 1000-a-b; // this is the only one target c, isn't?
16 
17             bool bFound = pow((float)c, 2== (pow((float)a, 2+ pow((float)b, 2));
18             if(bFound)
19                 goto end;
20         }
21     }        
22 
23 end:
24     cout << "a:" << a << endl;
25     cout << "b:" << b << endl;
26     cout << "c:" << c << endl;
27     long product = a*b*c;
28     cout << "abc:" << product << endl;
29 
30     return 0;
31 }

 

posted @ 2011-02-27 23:20  能巴  阅读(188)  评论(0)    收藏  举报