按需输出第K个质数,要找的质数靠后时,所需时间较长,这里给出几种最基本的求第K个质数的方法
法一
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<malloc.h>
#include<string.h>
//生成质数表
int* printPrimeList(int* arr)
{
arr = (int*)malloc(sizeof(int) *10000000);
int i, n, count = 0, tmp;
//printf("int primeNumber[] = {\n\t");
for(n = 2; n < 1000000; n++)
{
tmp = sqrt(n);
for(i = 2; i <= tmp; i++)
{
if(n % i == 0)
{
break;
}
}
if(i == tmp + 1)//寻找完毕
{
*(arr+count)=n;
// printf("%d, ", n);
count++;
// if(count % 10 == 0)
// {
// printf("\n\t");
// }
}
}
// for(i=0;i<count;i++){
// printf("%d ",arr[i]);
// }
//printf("};\n");
return arr;
}
//已知2是第一个素数,3是第二个、5是第三个……现在编程序求第k个素数是什么?所求素数均小于10000000。
int main()
{
int *a;
int *b=printPrimeList(a);
int n;
while(scanf("%d",&n)!=EOF){
printf("%llu\n",b[n-1]);
}
return 0;
}
法二
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<malloc.h>
#include<string.h>
int isPrime(int n)
{
int i,temp;
if(n<2){
return 0;
}else if(n==2){
return 1;
}else if(n%2==0){
//除2外的一切偶数均为合数
return 0;
}else{
//判断奇数,看能否被3~根号n 中的所有奇数整除
//能被其中任意一个奇数整除时,判定为合数
//所有奇数都不能被整除时,判定为质数
temp=sqrt(n);
for(i=3;i<=temp;i+=2)
{
if(n%i==0){
return 0;
}
}
return 1;
}
}
//生成质数表
int* printPrimeList(int* arr)
{
arr = (int*)malloc(sizeof(int) *665000);
int i, n, count = 0, tmp,f;
for(n = 2; n < 10000000; n++)
{
f=isPrime(n);
if(f)
{
*(arr+count)=n;
count++;
}
}
return arr;
}
//已知2是第一个素数,3是第二个、5是第三个……现在编程序求第k个素数是什么?所求素数均小于10000000。
int main()
{
int *a;
int *b=printPrimeList(a);
int n;
while(scanf("%d",&n)!=EOF){
printf("%llu\n",b[n-1]);
}
return 0;
}