Fermat vs. Pythagoras
Background
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 for n > 2.
The Problem
Given a positive integer N, you are to write a program that computes two quantities regarding the solution of
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 such that p is not part of any triple (not just relatively prime triples).
The 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.
The 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 ). The second number is the number of positive integers
that are not part of any triple whose components are all
. There should be one output line for each input line.
Sample Input
10 25 100
Sample Output
1 4 4 9 16 27
题意:找到勾股数三元组,并且其最大公约数为1的有多少种。以及不参与勾股数的数字有多少个。
思路:构造勾股数 a=n*n-m*m b=2*n*m c=n*n+m*m其中包括所有GCD(a,b,c)=1的,但不包含全部的勾股数。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int n,ans1,ans2,val[1000010];
int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
void solve()
{
int i,j,k,len=sqrt(n),a,b,c;
memset(val,0,sizeof(val));
ans1=0;ans2=n;
for(i=1;i<=len;i++)
for(j=i+1;j<=len;j++)
{
a=j*j-i*i;
b=2*i*j;
c=j*j+i*i;
if(c>n)
break;
if(gcd(gcd(a,b),c)==1)
{
ans1++;
for(k=1;k*c<=n;k++)
val[a*k]=val[b*k]=val[c*k]=1;
}
}
for(i=1;i<=n;i++)
ans2-=val[i];
}
int main()
{
int i,j,k;
while(~scanf("%d",&n))
{
solve();
printf("%d %d\n",ans1,ans2);
}
}