分段筛选eratosthenes spoj Prime1 C ++

时间:2016-01-02 08:02:54

标签: c++ runtime primes sieve-of-eratosthenes

我一直在努力解决这个问题http://www.spoj.com/problems/PRIME1/,如果有人能帮我找到代码中的错误。我使用了eratosthenes的分段筛,我也浏览了很多在线资源,但不知怎的,我在spoj上遇到运行时错误。 感谢

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <vector>
    #include <string>
    #include <cmath>
    #include <map>
    #include <cstdlib>
    #include <cassert>
    #define fora(i,a,b) for(i = a; i < b; i++)
    #define fin(f) freopen(f, "r", stdin)
    #define fout(f) freopen(f, "w", stdout)
    using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vll;
typedef vector<bool> vb;

const ll LIMIT = 1000000000;

void segmentedSieve(ll n, ll m, int segment_size) {
    int i, j, s, p, range;
    vb is_prime(range+1, true);
    vb seg_primes(segment_size+1, true);
    vi prime;

    range = floor(sqrt((double)n));

    fora (i, 2, range+1)
        if (is_prime[i]) {
            for (j = i*2; j <= range; j+=i)
                is_prime[j] = false;
        }

    fora (i, 2, range+1)
        if (is_prime[i] == 1)
            prime.push_back(i);

    fora (i, 0, prime.size()) {
        p = prime[i];
        s = m/p;
        s *= p;

        for (j = s; j <= n; j+=p) {
            if (j < m) continue;
            seg_primes[j-m] = false;
        }
    }

    fora (i, 0, prime.size())
        if (prime[i] >= m && prime[i] <= n) {
            cout << prime[i] << endl;
        }

    fora (i, 0, n-m+1)
        if (seg_primes[i] && (i+m) != 1) {
            cout << i+m << endl;
        }
}

int main()
{
    int segment_size = 100000;
    // fin("input.in");
    int t;
    cin >> t;
    while (t--) {
        ll a, b;
        cin >> a >> b;
        if (a > b)
            segmentedSieve(a, b, segment_size);
        else
            segmentedSieve(b, a, segment_size);
        if (t != 0)
            cout << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

range似乎未初始化:

void segmentedSieve(ll n, ll m, int segment_size) {
    int i, j, s, p, range;
    vb is_prime(range+1, true);   // uninitialized range... !!

也许你想要

void segmentedSieve(ll n, ll m, int segment_size) {
    int i, j, s, p, range;

    range = floor(sqrt((double)n));  // This first...

    vb is_prime(range+1, true);      // then this

如果可能,您应该在定义变量时初始化变量。

void segmentedSieve(ll n, ll m, int segment_size) {
    int i, j, s, p; // no range here

    int range = floor(sqrt((double)n));  // This first...

    vb is_prime(range+1, true);      // then this

一般情况下,你应该推迟变量的定义,直到你需要它们为止,即不要在开始时定义所有变量,而是在需要时进行变换。

P.S。正如其他人已经评论过的那样 - 摆脱所有那些宏观的东西......