我刚刚完成Project Euler问题9(警告剧透):
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案:
public static int specPyth(int num)
{
for (int a = 1; a < num; a++)
for (int b = 2; b < a; b++)
{
if (a*a +b*b == (num-a-b)*(num-a-b))
return a*b*(num-a-b); //ans = 31875000
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
我不禁想到有一个只涉及一个循环的解决方案.有人有想法吗?我更喜欢只使用一个循环的答案,但任何比我现在更有效的东西都会很好.
Fab*_*out 22
if a + b +c = 1000
Run Code Online (Sandbox Code Playgroud)
然后
a + b + sqroot(a² + b²) = 1000
-> (a² + b²) = (1000 - a - b)²
-> a² + b² = 1000000 - 2000*(a+b) + a² + 2*a*b + b²
-> 0 = 1000000 - 2000*(a+b) + 2*a*b
-> ... (easy basic maths)
-> a = (500000 - 1000*b) / (1000 - b)
Run Code Online (Sandbox Code Playgroud)
然后你尝试每一个b,直到你找到一个自然数字.
public static int specPyth(int num)
{
double a;
for (int b = 1; b < num/2; b++)
{
a=(num*num/2 - num*b)/(num - b);
if (a%1 == 0)
return (int) (a*b*(num-a-b));
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
编辑:b不能高于499,因为c> b和(b + c)将高于1000.
我强烈建议您阅读http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple并编写一个能够逐一生成毕达哥拉斯三元组的函数.
不要给太多的扰流板,但是有很多其他的PE问题,这个功能将派上用场.
(我不认为这太过分了,因为体育的一部分目的是鼓励人们学习这样的事情.)