请将不超过1993的所有素数从小到大排成第一行,第二行上的每个素数都等于它右肩上的素数之差。编写程序求第二行数中是否存在这样的若干个连续的整数,它们的和恰好是1898?假如存在的话,又有几种这样的情况

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
//判断数字是否为质数
bool isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) return false;
    }
    return true;
}
//生成所有小于1993的质数 
vector<int>GeneratePrimes(int limit) {
    vector<int>Primes;
    for (int i = 2; i <= limit; ++i) {
        if (isPrime(i)) {
            Primes.push_back(i);
        }
    }
    return Primes;
}
//生成各质数之间的差值
vector<int>GenerateDifferences(const vector<int>& Primes) {
    vector<int> Differences;
    for (size_t i = 0; i < Primes.size() - 1; ++i) {
        Differences.push_back(Primes[i+1] - Primes[i]);
    }
    return Differences;
}
//判断和为1898的情况有几种
int countContinuousSums(const vector<int>& Differences, int target) {
    int count = 0;
    for (size_t i = 0; i < Differences.size(); ++i) {
        int sum = 0;
        for (size_t j = i; j < Differences.size(); ++j) {
            sum += Differences[j];
            if (sum == target) {
                count++;
            }
            else if (sum > target) {
                break;
            }
        }
    }
    return count;
}
int main()
{
    int limit = 1993;
    int target = 1898;

    vector<int>Primes = GeneratePrimes(limit);
    vector<int>Differences = GenerateDifferences(Primes);
    int result = countContinuousSums(Differences,target);

    cout << "Number of ways to sum to " << target << " with consecutive differences: " << result << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值