寻找大素数C实现

找到一亿内所有素数并写入文件用时35秒.


#include "math.h"
#include "stdio.h"
#include "stdlib.h"
#include "time.h"

int isP(int num,int *p)
{
	int i;
	int len=p[0];
	int flag=1;
	p++;

	for(i=0;i<len && p[i]*p[i]<=num && flag;i++)
	{
		flag=num%p[i];
	}

	return flag;
}

int fun(int num)
{
	int cnt=(int)sqrt((double)num);

	if(cnt)
		while(num%cnt) cnt--;
	return cnt==1;
}

void main()
{
	int h=1000000;
	int l=2;
	int len=sqrt((double)h)+1;
	int n=len/log(len)+1;
	long i;
	clock_t start,end;
	int *a=(int)calloc(sizeof(int),(int)(2*len/log(len)));
	FILE *fp=fopen("p.txt","w");

	a[0]=1;
	a[1]=2;

	for(i=3;i<len;i+=2) 
		if(isP(i,a))
			a[++a[0]]=i;

	printf("num:%d,n:%d,len:%d\n",a[0],(int)(3*len/(log(len)*2)),len);

	start=clock();

	if(2<=l) fprintf(fp,"%d\n",2);
	for(i=l+!(l%2);i<=h;i+=2)
		if(isP(i,a))
			fprintf(fp,"%d\n",i);

	end=clock();

	fclose(fp);

	printf("%f\n",(double)(end-start)/CLOCKS_PER_SEC);

	free(a);
}

你可能感兴趣的:(素数,大数,大素数)