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

相关推荐
2401_8321319530 分钟前
模板错误消息优化
开发语言·c++·算法
金枪不摆鳍31 分钟前
算法--二叉搜索树
数据结构·c++·算法
近津薪荼35 分钟前
优选算法——双指针6(单调性)
c++·学习·算法
helloworldandy1 小时前
高性能图像处理库
开发语言·c++·算法
2401_836563181 小时前
C++中的枚举类高级用法
开发语言·c++·算法
bantinghy1 小时前
Nginx基础加权轮询负载均衡算法
服务器·算法·nginx·负载均衡
chao1898441 小时前
矢量拟合算法在网络参数有理式拟合中的应用
开发语言·算法
代码无bug抓狂人1 小时前
动态规划(附带入门例题)
c语言·算法·动态规划
weixin_445402302 小时前
C++中的命令模式变体
开发语言·c++·算法
季明洵2 小时前
C语言实现顺序表
数据结构·算法·c·顺序表