寻找大于n的第一个质数

寻找大于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

如果哪位还有更好的解决办法,多赐教!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值