题目描述:
算法思想:
- 左边界:初始值如下
int pre=c,next=c,numLen=0,res=c;
- 区间中:先求出质数,然后根据上一个质数pre和next质数的区间长度判定是否改变res和numLen。改变res和numLen即可改变最大合数区间(res+1,res+numLen);
while((next<=d)&&(next>=c)){
int flag = 1;
// 判断next是否为素数
for(int i=2;i<=sqrt(next);i++){
if(next%i==0){
flag=0;
break;
}
}
// 为质数, pre除初始值外一定是质数
if(flag){
int tmp = next-pre-1;
if(numLen<tmp){
numLen = tmp;
res = pre;
}
pre=next;
}
// next移动
next++;
}
- 右边界:上一步在while循环中,只考虑了质数与质数之间的合数区间,没有考虑边界。执行完while循环后,还需要判定pre和d的区间长度,在判定是否对合数区间进行改变。
int tmp = d-pre-1;
if(tmp>numLen){
numLen = tmp;
res = pre;
}
完整代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int main(){
int c,d;
cin>>c>>d;
int pre=c,next=c,numLen=0,res=c;
while((next<=d)&&(next>=c)){
int flag = 1;
// 判断next是否为素数
for(int i=2;i<=sqrt(next);i++){
if(next%i==0){
flag=0;
break;
}
}
// 为质数, pre除初始值外一定是质数
if(flag){
int tmp = next-pre-1;
if(numLen<tmp){
numLen = tmp;
res = pre;
}
pre=next;
}
// next移动
next++;
}
// 最后一个质数与右边界d的情况
int tmp = d-pre-1;
if(tmp>numLen){
numLen = tmp;
res = pre;
}
cout<<"合数区间"<<res+1<<' '<<res+numLen<<endl; // pre为最大质数但不一定最大合数区间的左边质数
cout<<"个数"<<numLen<<endl;
return 0;
}