欧拉计划50题

Consecutive prime sum

The prime 41, can be written as the sum of six consecutive primes:

41 = 2 + 3 + 5 + 7 + 11 + 13

This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most consecutive primes?
题目:

41 这个质数,可以写作 6 个连续质数之和:

41 = 2 + 3 + 5 + 7 + 11 + 13

这是 100 以下的最长的和为质数的连续质数序列。

1000 以下最长的和为质数的连续质数序列包含 21 个项,和为 953。

找出 100 万以下的最长的何为质数的连续质数序列之和。

100 万以下的哪个质数能够写成最长的连续质数序列?
题目要求连续质数最长,并且这个连续质数之和小于100万,那么进行分析:

1.求出100以下的质数,线性筛

2.求出每个质数加上之前质数的和,假如当前质数为5,那么他的和就为10

3.求道每个质数加上之前的和后,进行开始枚举,因为题目给出了1000以下最长是21,那么就两个循环,外循环就从2开始,那么内循环就从2往后移21个质数的位置开始,那么就有22个连续的质数,用一个变量存现在最长的连续质数的长度,进行实时更新,如果发现改变就更新,也更新他们的和;

通过3个分析就可以求得最后的结果,下面的代码实现:

cpp 复制代码
#include <stdio.h>
#define MAX_N 1000000

int prime[MAX_N + 5];
int isprime[MAX_N + 5];
int sum[MAX_N + 5];

void init() {//线性筛
    for (int i = 2; i <= MAX_N; i++) {
        if (!isprime[i]) prime[++prime[0]] = i;
        for (int j = 1; i * prime[j] <= MAX_N; j++) {
            isprime[i * prime[j]] = 1;
            if (i % prime[j] == 0) break;
        }
    }
}

int main() {
    init();
    sum[0] = 0;
    for (int i = 1; i <= prime[0]; i++) {//求每个质数加上前面质数的和
        sum[i] = sum[i - 1] + prime[i];
    }
    int ans = 953, ind = 21;
    for (int i = 0; i <= prime[0]; i++) {//从0开始就是,从2-小于100万的最后一个质数去判断
        for (int k = i + 1 + ind; k <= prime[0]; k++) {
            int s = sum[k] - sum[i];
            if (s >= MAX_N) break;//防止越界
            if (isprime[s]) continue;//如果不为质数那么就继续往后循环
            ans = s;
            ind = k - i;//更新长度
        }
    }
    printf("%d %d\n", ans, ind);
    return 0;
}

最终答案 : 997651 长度为543

相关推荐
吴可可12314 分钟前
Accumark二次开发环境搭建与API入门
算法
木井巳2 小时前
【动态规划: 线性dp】解码方法
java·算法·leetcode·动态规划·推荐算法
春弦_9 小时前
自用算法整理二
数据结构·算法·图论
hetao173383710 小时前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
java_nnnn11 小时前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展
Navigator_Z12 小时前
LeetCode //C - 1301. Number of Paths with Max Score
c语言·算法·leetcode
卡卡~~12 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
企业数字化笔记13 小时前
AI视频增强后画质怎么验收?插值基线、伪细节与帧间闪烁的检查方法
人工智能·算法·音视频
学逆向的13 小时前
C 内存属性
c语言·开发语言·算法·网络安全