Codility代码导致分段错误

时间:2014-02-21 22:18:28

标签: c++ primes

这是我的Count Semiprimes codility问题的解决方案,这对于中小型输入是正确的,但是导致大型测试用例的分段错误。

https://codility.com/demo/results/demo8JU794-FC7/

这通常发生在无效指针等处。但是我在这里看不到任何可能导致此类行为的内容。

您是否能够发现代码有任何问题?

vector<int> solution(int N, vector<int> &P, vector<int> &Q) {

    int M = P.size();

    // Use sieve of eratosthenes to find prime numbers within range 0 to N
    vector<int> sieve(N+1);
    sieve[0] = sieve[1] = 0;

    for (int i = 2; i <= N; ++i)
    {
        if (sieve[i] == 0)
        {
            int k = i * i;
            while(k <= N)
            {
                // For each non prime store its lowest prime divisor.
                sieve[k] = i;
                k += i;
            }
        }
    }

    vector<int> answer(M);

    for (int i = 0; i < M; ++i)
    {
        // Count semiprimes for each range (P[i], Q[i])
        int count = 0;

        for(int j = P[i]; j <= Q[i]; ++j)
        {
            // If a number is divisible by prime and the result of this division is also a prime
            // Then it's a semiprime.
            if (sieve[j] != 0 && sieve[j / sieve[j]] == 0)
            {
                count++;
            }
        }
        answer[i] = count;
    }

    return answer;
}

2 个答案:

答案 0 :(得分:2)

在这部分中,对于N = 50000,k = i * i的结果溢出了一个int,这就是segfault的原因。

    if (sieve[i] == 0)
    {
        int k = i * i;
        while(k <= N)
        {
            // For each non prime store its lowest prime divisor.
            sieve[k] = i;
            k += i;
        }
    }

答案 1 :(得分:0)

你能发布seg故障的位置吗?

仅从外观来看,当N为0时,sieve[0] = sieve[1] = 0;将表现出未定义的行为。