题目:
A Pythagorean triplet is a set of three natural numbers, a b
c, for which,
a
2 +
b
2 =
c
2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
算法:
#!/usr/bin/env python
#coding=utf-8
i = 1
while True:
a = i*2 + 1
b = (i**2)*2+i*2
c = b + 1
temp = 1000%(a+b+c)
if temp == 0:
temp = 1000/(a+b+c)
print a*temp*b*temp*c*temp
exit()
elif a+b+c < 1000:
i += 2
else:
break
i = 2
while True:
a = i*2
b = i**2 - 1
c = b + 2
temp = 1000%(a+b+c)
if temp == 0:
temp = 1000/(a+b+c)
print a*temp*b*temp*c*temp
exit()
elif a+b+c < 1000:
i += 2
else:
break
结果:31875000
如果a,b,c是一组勾股数,那么na,nb,nb也是勾股数,所以只要求出一组互质的勾股数就可以得出任意组。而求互质的勾股数有一个公式:
当a为大于1的奇数2n+1时,b=2*n^2+2*n, c=2*n^2+2*n+1
当a为大于4的偶数2n时,b=n^2-1, c=n^2+1
按照这个公式,求出一组满足a+b+c可以整除1000的勾股数,然后将a,b,c扩大到和为1000就是结果。
以后估计就只能抽空做做这上边的题了。做完这道题得到一个勋章:
java代码:
package ten;
public class Problem9 {
public static void main(String args[]){
int i=1,a=0,b=0,c=0,temp=0;
while(true){
if(i%2 == 1){
a = i*2 + 1;
b = (i*i)*2 + i*2;
c = b +1;
}
else{
a = i*2;
b = i*i - 1;
c = b + 2;
}
temp = 1000%(a+b+c);
if(temp == 0){
temp = 1000/(a+b+c);
System.out.println(a*b*c*temp*temp*temp);
System.exit(0);
}
else if(a+b+c<1000){
i++;
}
else{
break;
}
}
}
}