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

相关推荐
网安INF8 分钟前
SHA-1算法详解:原理、特点与应用
java·算法·密码学
无聊的小坏坏23 分钟前
从数学到代码:一文详解埃拉托色尼筛法(埃式筛)
算法
Gyoku Mint1 小时前
机器学习×第七卷:正则化与过拟合——她开始学会收敛,不再贴得太满
人工智能·python·算法·chatgpt·线性回归·ai编程
黑听人1 小时前
【力扣 中等 C++】90. 子集 II
开发语言·数据结构·c++·算法·leetcode
黑听人1 小时前
【力扣 简单 C】21. 合并两个有序链表
c语言·开发语言·数据结构·算法·leetcode
励志成为大佬的小杨2 小时前
时间序列基础
人工智能·算法
黑听人2 小时前
【力扣 简单 C】83. 删除排序链表中的重复元素
c语言·开发语言·数据结构·算法·leetcode
微凉的衣柜2 小时前
机器人导航中的高程图 vs 高度筛选障碍物点云投影 —— 如何高效处理避障问题?
算法·机器人
Shaun_青璇2 小时前
Cpp 知识3
开发语言·c++·算法
小鸡脚来咯3 小时前
ThreadLocal实现原理
java·开发语言·算法