我刚刚完成了 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.
这是我的解决方案:
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;
}
我不禁想到有一种解决方案只涉及一个循环。有人有想法吗?我更喜欢只使用一个循环的答案,但任何比我目前拥有的更有效的东西都会很好。