解题思路要解决这个问题,我们需要找到数列 ({2,3,\cdots,n}) 中连续非素数子序列的最大长度。为此,我们可以采用以下步骤:筛法求素数:使用埃拉托斯特尼筛法(Sieve of Eratosthenes)快速标记出所有素数。统计连续非素数:遍历数列,统计每个连续非素数段的长度,并记录最大值。代码实现下面是优化后的代码实现:
#include <bits/stdc++.h> using namespace std;
const int MAXN = 5e6 + 5; bool isPrime[MAXN]; // 标记数组,isPrime[i] 为 false 表示 i 是素数
int main() { int n; cin >> n;
// 初始化筛法数组
memset(isPrime, false, sizeof(isPrime));
isPrime[0] = isPrime[1] = true; // 0和1不是素数
// 埃拉托斯特尼筛法
for (int i = 2; i * i <= n; ++i) {
if (!isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = true;
}
}
}
// 统计最长连续非素数子段
int maxLen = 0, currentLen = 0;
for (int i = 2; i <= n; ++i) {
if (isPrime[i]) {
++currentLen;
maxLen = max(maxLen, currentLen);
} else {
currentLen = 0;
}
}
cout << maxLen << endl;
return 0;
}
代码解释筛法求素数:初始化一个布尔数组 isPrime,其中 isPrime[i] 为 false 表示 i 是素数,true 表示 i 是非素数。使用埃拉托斯特尼筛法,从 2 开始遍历到 (\sqrt{n}),将每个素数的倍数标记为非素数。优化点在于内层循环从 i*i 开始,避免重复标记。统计最长连续非素数:遍历数列 ({2,3,\cdots,n}),维护两个变量:currentLen 记录当前连续非素数的长度,maxLen 记录历史最大长度。当遇到非素数时,currentLen 加 1 并更新 maxLen;遇到素数时,重置 currentLen 为 0。