POJ1305(Fermat vs. Pythagoras 毕达哥拉斯三元组解不定方程)

来源:互联网 发布:程序员和工程师的区别 编辑:程序博客网 时间:2024/04/28 18:34
Fermat vs. Pythagoras
Time Limit: 2000MS Memory Limit: 10000KTotal Submissions: 1412 Accepted: 821

Description

Computer generated and assisted proofs and verification occupy a small niche in the realm of Computer Science. The first proof of the four-color problem was completed with the assistance of a computer program and current efforts in verification have succeeded in verifying the translation of high-level code down to the chip level. 
This problem deals with computing quantities relating to part of Fermat's Last Theorem: that there are no integer solutions of a^n + b^n = c^n for n > 2. 
Given a positive integer N, you are to write a program that computes two quantities regarding the solution of x^2 + y^2 = z^2, where x, y, and z are constrained to be positive integers less than or equal to N. You are to compute the number of triples (x,y,z) such that x < y < z, and they are relatively prime, i.e., have no common divisor larger than 1. You are also to compute the number of values 0 < p <= N such that p is not part of any triple (not just relatively prime triples). 

Input

The input consists of a sequence of positive integers, one per line. Each integer in the input file will be less than or equal to 1,000,000. Input is terminated by end-of-file

Output

For each integer N in the input file print two integers separated by a space. The first integer is the number of relatively prime triples (such that each component of the triple is <=N). The second number is the number of positive integers <=N that are not part of any triple whose components are all <=N. There should be one output line for each input line.

Sample Input

1025100


Sample Output

1 44 916 27


题目大意:

给定一个整数n,分别求n范围内的本原的毕达哥拉斯三元组的个数,以及n以内且毕达哥拉斯三元组不涉及数的个数.

解题思路:

本原毕达哥拉斯三元组满足:
x = m ^ 2 - n ^ 2 (m > n && n 为偶数,m要为奇数,m为奇数,n要为偶数)
y = 2 * m * n
i * z = m ^ 2 + n ^ 2
所以我们只要在给定的范围内枚举,m,n便可以,因为题目要求(x,y,z <= n)所以只要m ^ 2 + n ^ 2 > n枚举便退出,当求出一组最小的x,y,z,之后便可以枚举i * z <= n之内所有的,x,y,z,每次统计个数便可。

AC代码:
/*x = m ^ 2 - n ^ 2y = 2 * m * ni * z = m ^ 2 + n ^ 2*/#include<iostream>#include<cmath>#include<cstring>using namespace std;const int maxn = 1000001;bool flag[maxn];int gcd(int a,int b){return b == 0 ? a : gcd(b,a % b);}void solve(int num){int i,j;int x,y,z;int c;int ans1 = 0;int ans2 = 0;int temp;temp = sqrt(num + 0.0);for(i=1;i<=temp;i++)  //枚举m {for(j=i+1;j<=temp;j++) //枚举n {if(i * i + j * j > num){break;}if(i % 2 != j % 2){if(gcd(j,i) == 1){x = j * j - i * i;y = 2 * i * j;z = i * i + j * j;ans1++;for(c=1;;c++){if(c * z > num){break;}flag[c * x] = true;flag[c * y] = true;flag[c * z] = true;//cout<<"x:"<<c*x<<" "<<"y:"<<c * y<<" "<<"z:"<<c * z<<endl;}}}}}for(i=1;i<=num;i++){if(!flag[i]){ans2++;}}printf("%d %d\n",ans1,ans2);}int main(){int m;while(scanf("%d",&m) != EOF){memset(flag,false,sizeof(flag));solve(m);}return 0;} 


0 0
原创粉丝点击