Skip to content

Instantly share code, notes, and snippets.

@LYP951018
Created December 11, 2014 11:19
Show Gist options
  • Save LYP951018/8cb35c9dc25073afa877 to your computer and use it in GitHub Desktop.
Save LYP951018/8cb35c9dc25073afa877 to your computer and use it in GitHub Desktop.
#define __STDC__WANT__LTB__ 1
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<stdint.h>
#define CAP_INCR 10
int main(void)
{
uint64_t *pPrimes=NULL;//定义指针及变量
uint64_t *pTemp=NULL;
bool found=false;
uint64_t limit=0LL;
int count=0;
uint64_t trial;
printf("请输入质数上限值:");
scanf("%llu",&limit);
size_t capacity=10;//分配内存
pPrimes=calloc(capacity,sizeof(uint64_t));
if(!pPrimes)
{
printf("内存不足,无法进行之后的操作。\n");
return 1;
}
*pPrimes=2ULL;//开头给出2、3、5
*(pPrimes+1)=3ULL;
*(pPrimes+2)=5ULL;
count=3;//记录质数个数为3
trial=*(pPrimes+2)+2ULL;//测试的变量
while(trial<=limit)//测试变量
{
for(int i=1;i<count;++i)
{
uint64_t temp;
temp=*(pPrimes+i);
if(!(found=(trial%temp)))
break;
}
if(found)
{
if(count==capacity)
{
capacity += CAP_INCR;
pTemp=realloc(pPrimes,capacity*sizeof(uint64_t));
if(!pTemp)
{
printf("内存再分配失败。\n");
free(pPrimes);
pPrimes=NULL;
return 2;
}
pPrimes=pTemp;
}
*(pPrimes+count++)=trial;
}
trial+=2ULL;
}
printf("%d primes found up to %llu:\n",count,limit);
for(int i=0;i<count;++i)
{
printf("%12llu",*(pPrimes+i));
if(!((i+1)%5))
printf("\n");//确保换行
}
printf("\n");
free(pPrimes);//释放内存并指向NULL
pPrimes=NULL;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment