Question

Here's my solution for Count Semiprimes codility problem, which is correct for small and medium inputs but results in segmentation fault for large test cases.

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

This normally happens with invalid pointers etc. however I can't see anything here which could cause such behaviour.

Are you able to spot anything wrong with the code?

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;
}
Was it helpful?

Solution

In this part, for N = 50000 the result of k = i * i overflows an int which is the reason for the 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;
        }
    }

OTHER TIPS

Can you post where the seg fault is at?

Just from the looks, sieve[0] = sieve[1] = 0; will exhibit undefined behavior when N is 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top