我刚刚完成了项目欧拉问题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; }
我不禁想到有一个只有一个循环的解决方案.有人有想法吗?我只想使用一个循环,但是比现在更有效的任何东西都会很好.
解决方法
if a + b +c = 1000
然后
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)
然后你尝试每一个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; }
编辑:b不能高于499,因为c> b和(b c)然后将高于1000.