寻找大于n的第一个质数,如n=7,则第一个质数为11.
思路:何为质数?只能被1和本身整除的自然数(大于1)就是质数。我们判断一个数i是否为质数时,就要依次被(2、3、4...i-2、i-1)除,若全不能整除则判断为质数。这样的逻辑恐怕非常容易实现,但效率不高。我们可以想下,如果不能被2整除的话,咱们还需要考虑(i/2、i/2+1、i/2+2...i-2、i-1)这些数吗?1<i/(i/2+1)<2,若能整除至少商应该是个整数吧。不能被3整除呢?依次类推,我们只需要考虑(2——i的开平方后最大的整数)这之间的数是否能整除i就可以了。下面是c语言的实现:
#include<stdio.h>
#include<stdlib.h>
int get_first_prime(int n)
{
int i,j;
int res;
int order=0;//计算找到质数时需要次数
for(i=n+1;i<2*n;i++)//我们寻找的是第一个质数,所以要小于2n
{
printf("now i = %d\n",i);
for(j=2;j<(i/j+1);j++)//本例的思路
{
order++;
res=i/j;
printf("res=%d\n",res);
if((res-j)<=1 && i%j!=0)//本例的关键
{
printf("order is %d\n",order);
return i;
}
if(i%j == 0)
{
printf("not ok :%d,and the first div is :%d\n",i,j);
break;
}
else
continue;
}
}
printf("order is %d\n",order);
return 0;
}
int main()
{
int n;
printf("Input value:\n");
scanf("%d",&n);
printf("n=%d\n",n);
int res =0;
res=get_first_prime(n);
printf("the first prime behind %d is %d\n",n,res);
return 0;
}
编译后运行结果如下:
$ gp
Input value:
120
n=120
now i = 121
not ok :121,and the first div is :11
now i = 122
not ok :122,and the first div is :2
now i = 123
not ok :123,and the first div is :3
now i = 124
not ok :124,and the first div is :2
now i = 125
not ok :125,and the first div is :5
now i = 126
not ok :126,and the first div is :2
now i = 127
order is 29
the first prime behind 120 is 127
如果哪位还有更好的解决办法,多赐教!