1.关于勾股数的枚举
x*x+y*y=z*z-> x=m*m-n*n
->y=2*m*n;
->z=m*m+n*n;
如果单个的枚举x,y,z的话,如果枚举到100万,那么肯定超时,但是借用这个公式的话,我们只需要对m,n枚举,也就是说我们只需要枚举到根号100万,时间复杂度直接大大减少,绝对不超时
其次,还有一个判断是否是素勾股数的办法就是如果 m,n至少有一个为偶数,并且m,n互质,那么x,y,z就是素勾股数
还有就就是判断是否互质的问题,2个数,除了1以外没有多余的公约数,那么这2个数就数就互质,所以说1与任何数互所以说2和4是互质的(妹子的=-=。。一开始不知道)
2. 关于如何算出非勾股数的个数问题
这个问题我一开始很头疼,因为他开到了100W的取值范围,而C上面的数组最多开到50W,所以说想拿数组去代换是不可能的,而动态内存的分配又不知道怎么弄,最后参考了别人的资料(原谅我吧。。。我实在没招了)只好拿C++里面的bool型数组来做!!!这个bool型数组可以开到100W的,先算出和勾股数有关的数的个数再用n-counts得到了非勾股数
下面上题上代码
Fermat vs. Pythagoras
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 thatp 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
#include<stdio.h>
#include<string.h>
#include<math.h>
#define MAX_SIZE 1000000 + 10
bool array[MAX_SIZE]; /*这里用到了C++的bool数组*/
int judge(int m,int n)
{
int i;
if(m%2==1&&n%2==1) /*进行素三角形的判断*/
return 0;
for(i=2;i<=n;i++)
if(n%i==0&&m%i==0)
return 0;
return 1;
}
int main()
{
int N,m,n,i;
int x,y,z;
while(scanf("%d",&N)!=EOF)
{
memset(array,0,sizeof(array));
int num=0;
int counts=0;
for(n=1;n<=sqrt(N);n++)
for(m=n+1;m<=sqrt(N);m++)
{
x=m*m-n*n;
y=2*m*n;
z=m*m+n*n; /*m一定要大于n*/
if(x*x+y*y==z*z&&judge(m,n)==1&&z<=N)
{
num++;
}
for(i=1;i*z<=N;i++)/*计算勾股数的个数*/
{
if(array[x*i]==0)
{
array[x*i]=1;
counts++;
}
if(array[y*i]==0)
{
array[y*i]=1;
counts++;
}
if(array[z*i]==0)
{
array[z*i]=1;
counts++;
}
}
}
printf("%d %d\n",num,N-counts);
}
return 0;
}
关于这道题只能说我了解还是太少了,一道十分简单的数论题弄的我一点思路没有,就是因为知道了太少了,比如勾股数的判定,以及C++bool数组的用法,这些都是要在以后的做题和看数中学习的。