タイトルの説明:
アルゴリズムのアイデア:
- 左マージン:初期値は以下の通りです
int pre=c,next=c,numLen=0,res=c;
- 間隔内:最初に素数を見つけ、次に最後の素数の前と次の素数の間隔の長さに応じて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;
}