Prime Sieve

Can somebody explain why I am getting a runtime error when I am calculating prime sieve up to 10^6 & 10^5? It is working fine for 10^4;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n = 10000;
    bool sieve[n];

    for(int i = 2; i < n; i++)
        if(i%2==0)
            sieve[i] = false;
        else sieve[i] = true;

    sieve[0] = sieve[1] = false;
    sieve[2] = true;

    for(int p = 3; p < n; p += 2)
        for( int i = p * p; i < n; i += 2*p)
            if(sieve[i])
                sieve[i] = false;

    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;

        if(n%2!=0 && sieve[n] )
            cout << "Prime" << endl;
        else if(n==2) cout << "Prime" << endl;
        else cout << "Not Prime" << endl;
    }
    return 0;
}
You are trying to access an element in sieve that doesn't exist past 10,000:

if(n%2!=0 && sieve[n] )

Any input greater than 10,000 is invalid and will produce either garbage output or will crash the program
To complete what zapshe said, I would say "use a vector, vectors are good".
Another option would be to use std::bitset.
http://www.cplusplus.com/reference/bitset/bitset/
@zapshe here if I do n=10^6 or n=10^5, i am getting run time error.

the uploaded code has n=10^4 and is working fine and I am not accessing 10^5 or 10^6 here.

@zaap tried vectors also.
Last edited on
Well, you do have two variables called n. Which isn't helping you.

You are also making p an int. So, when you form p * p you are hoping that it stays within the range of an int. In the case of n=105 that is probably not true. On line 18, p only has to go up to (and including, where appropriate) the square root of n.

Basically, you are overflowing the maximum value that an int can hold.
Last edited on
@lastchance
Thank you. I got it. Here is my updated code which is running fine for 10^6.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n = 1000001;
    bool sieve[n];

    for(int i = 2; i < n; i++)
        if(i%2==0)
            sieve[i] = false;
        else sieve[i] = true;

    sieve[0] = sieve[1] = false;
    sieve[2] = true;

    for(int p = 3; p < sqrt(n); p += 2)
        for( int i = p*p; i < n; i += 2*p)
            if(sieve[i])
                sieve[i] = false;

    int t;
    cin >> t;
    while(t--)
    {
        int n1;
        cin >> n1;

        if(n1%2!=0 && sieve[n1] )
            cout << "Prime" << endl;
        else if(n1==2) cout << "Prime" << endl;
        else cout << "Not Prime" << endl;
    }
    return 0;
}

Topic archived. No new replies allowed.