c++ - 无法理解为什么我的程序会抛出错误

标签 c++ algorithm

我的代码在

#include <iostream>
#include <string>
#include <algorithm>
#include <climits> 
#include <vector>
#include <cmath>

using namespace std;

struct State {
    int v;
    const State *rest;
    void dump() const {
        if(rest) {
            cout << ' ' << v;
            rest->dump();
        } else {
            cout << endl;
        }
    }
    State() : v(0), rest(0) {}
    State(int _v, const State &_rest) : v(_v), rest(&_rest) {}
};

void ss(int *ip, int *end, int target, const State &state) {
    if(target < 0) return; // assuming we don't allow any negatives
    if(ip==end && target==0) {
        state.dump();
        return;
    }
    if(ip==end)
        return;
    { // without the first one
        ss(ip+1, end, target, state);
    }
    { // with the first one
        int first = *ip;
        ss(ip+1, end, target-first, State(first, state));
    }
}

vector<int> get_primes(int N) {
    int size = floor(0.5 * (N - 3)) + 1;

    vector<int> primes;
    primes.push_back(2);
    vector<bool> is_prime(size, true);

    for(long i = 0; i < size; ++i) {
       if(is_prime[i]) {
           int p = (i << 1) + 3;
           primes.push_back(p);
           // sieving from p^2, whose index is 2i^2 + 6i + 3
           for (long j = ((i * i) << 1) + 6 * i + 3; j < size; j += p) {
               is_prime[j] = false;
           }
       }
    }
}

int main() {
    int N;
    cin >> N;
    vector<int> primes = get_primes(N);

    int a[primes.size()];

    for (int i = 0; i < primes.size(); ++i) {
        a[i] = primes[i];
    }

    int * start = &a[0];
    int * end = start + sizeof(a) / sizeof(a[0]);
    ss(start, end, N, State());
}

它接受一个输入 N (int),并得到所有小于 N 的素数的vector

然后,它从 vector 中找到唯一集合的数量,这些集合加起来为 N

get_primes(N) 有效,但另一个无效。

我借用了其他代码 How to find all matching numbers, that sums to 'N' in a given array

请帮帮我..我只想要唯一集的数量。

最佳答案

您忘记了在 get_primes() 函数的末尾return primes;

关于c++ - 无法理解为什么我的程序会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28227800/

相关文章:

c++ - 如何将 c++ 变量的值传递给 hadoop HDFS 的 bash 系统命令?

c++ - 在多线程 C++11 程序中未处理异常时会发生什么?

c++ - 如何计算朱利安算术

c++ - C++ 日志框架会牺牲可重用性吗?

图像变形 - 凸起效应算法

string - 将字符串划分为包括空分区在内的子字符串的算法

c++ - if/else 的 Else 组件未执行 (C++)

python - 在匹配另一个模式的字符串中找到最短子串的开始和结束索引

algorithm - 红黑树如何旋转

c++ - boost中rtree中的打包算法