POJ 1305 勾股数的构造

来源:互联网 发布:个人云计算怎么赚钱 编辑:程序博客网 时间:2024/06/06 10:47

题目连接:http://poj.org/problem?id=1305

 

题目是叫我们去求小于n的勾股原数组的个数

 

熟悉数论的同学或许记得那个本原勾股数组的公式

a=s*t,b=(s*s-t*t)/2,c=(s*s+t*t)/2

其中s>t>=1而且gcd(s,t)==1

参见《数论概论》第二章勾股数组

 

所以下面的任务就很轻松了,只需要暴力求解就可以了

POJ的数据很弱,所以0秒就可以AC了

 

我的代码:

Source Code

Problem: 1305 User: bingshenMemory: 1140K Time: 0MSLanguage: C++ Result: Accepted

  • Source Code
    #include<stdio.h>#include<math.h>#include<string.h>bool flag[1000005];__int64 gcd(__int64 a,__int64 b){if(b==0)return a;elsereturn gcd(b,a%b);}int main(){__int64 n,s,t,a,b,c,ans1,ans2,i;while(scanf("%I64d",&n)!=EOF){ans1=0,ans2=0;memset(flag,0,sizeof(flag));for(t=1;t<=n;t=t+2){for(s=t+2;s<=n;s=s+2){if(gcd(s,t)!=1)continue;a=s*t;b=(s*s-t*t)/2;c=(s*s+t*t)/2;if(c>n)break;ans1++;for(i=1;c*i<=n;i++){flag[i*a]=true;flag[i*b]=true;flag[i*c]=true;}}}for(i=1;i<=n;i++)if(!flag[i])ans2++;printf("%I64d %I64d/n",ans1,ans2);}return 0;}