Problem 9
Special Pythagorean triplet
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.
特殊毕达哥拉斯三元组
毕达哥拉斯三元组是三个自然数a < b < c组成的集合,并满足
a2 + b2 = c2
例如,32 + 42 = 9 + 16 = 25 = 52。
有且只有一个毕达哥拉斯三元组满足 a + b + c = 1000。求这个三元组的乘积abc。
代码演示
#include<iostream>
#include<cmath>
using namespace std;
int gcd(int a,int b){
return (b? gcd(b,a%b):a);
}
int main(){
int ans=0;
for(int n=1;n<=33;n++){
for(int m=n+1;m*m+n*n<=1000 && !ans;m++){
if(gcd(n,m)!=1)continue;
int a=2*m*n;
int b=m*m-n*n;
int c=m*m+n*n;
if(1000%(a+b+c)==0){
int k=1000/(a+b+c);
cout<<k<<endl;
ans=a*b*c*(int)pow(k,3);
}
if(ans) break;
}
if(ans)break;
}
cout<<ans<<endl;
return 0;
}