欧拉计划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

相关推荐
CVer儿2 分钟前
svd分解求旋转平移矩阵
线性代数·算法·矩阵
Owen_Q10 分钟前
Denso Create Programming Contest 2025(AtCoder Beginner Contest 413)
开发语言·算法·职场和发展
Wilber的技术分享1 小时前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
Tanecious.1 小时前
LeetCode 876. 链表的中间结点
算法·leetcode·链表
Wo3Shi4七2 小时前
哈希冲突
数据结构·算法·go
呆呆的小鳄鱼2 小时前
cin,cin.get()等异同点[面试题系列]
java·算法·面试
Touper.2 小时前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun0077002 小时前
std::forward作用
开发语言·c++·算法
JoernLee2 小时前
机器学习算法:支持向量机SVM
人工智能·算法·机器学习
V我五十买鸡腿3 小时前
顺序栈和链式栈
c语言·数据结构·笔记·算法