C语言小项目之找指定个数的质数

软件:    VS2010

介绍:手动输入要找几个质数,就从2,3,5开始往后找质数,详情见注释

#define _STDC_WANT_LTB_EXT1_ 1
#define false 0
#define true 1
#include
#include

int main(void)
{
	unsigned long long *pPrimes = NULL;	//定义并初始化指针
	unsigned long long trial = 0;
	int found = false;
	int total = 0;
	int count = 0;
	int i;

	printf("How many primes would you like - you'll get at least 4\n");	//primes的中文意思是质数,你想要多少个质数
	printf("请输入你需要找多少个质数(注意:质数从2开始):");
	scanf_s("%d",&total);	//total表示我们需要找几个质数
	total = total < 4 ? 4 : total;	//运算符优先级顺序(从高到低):<,?:,=		保证total>=4 

	pPrimes = (unsigned long long*)malloc(total*sizeof(unsigned long long));	//动态分配内存
	if(!pPrimes)
	{
		printf("Not enough memory.It's the end I'm afraid.\n");
		return 1;
	}
	*pPrimes = 2ULL;
	*(pPrimes + 1) = 3ULL;
	*(pPrimes + 2) = 5ULL;
	count = 3;	//已经知道的并存储的质数,2,3,5,共有3个
	trial = 5ULL;	//最后一个知道并有的质数是5

	//找到所有符合要求的质数
	while(count < total)
	{
		trial += 2ULL;	//因为其他质数必定是奇数,所以每次在最后一个质数5上加2
		
		//
		for(i = 1; i < count; ++i)	
		{
			if(!(found = (trial % *(pPrimes + i))))	//found=0表示trial能被之前小的质数整除,那么该trial就不是质数;found!=0表示trial不能被之前的质数整除;	i=1的原因是trial += 2ULL,保证了其一定是奇数,所以直接%3开始
				break;
		}
		if(found)
			*(pPrimes + count++) = trial;	//每发现符合要求的质数,就将count+1
	}

	//
	printf("\n显示打印的结果:");
	for(i = 0; i < total; ++i)
	{
		printf("%12llu", *(pPrimes + i));
		if(!((i+1)%5))    //以5个一行输出质数
			printf("\n");
	}
	printf("\n");

	//释放动态内存
	free(pPrimes);
	pPrimes = NULL;
	return 0;
}

结果截图:

C语言小项目之找指定个数的质数_第1张图片

你可能感兴趣的:(C)