Process returned -1073741819 (0xC0000005) (why though??)

0

So i was solving my homework, and i did this piece of code which is supposed to find the biggest difference beetween two prime numbers in the interval of [a,b], and i got "Process returned -1073741819 (0xC0000005)"

#include <iostream>
#include <vector>
#include <bitset>

using namespace std;
bitset <10000000>v;
int main()
{
    for (int i = 2; i < 10000000; i++)
    {
        if (v[i] == 0)
        {
            for (int j = i * i; j < 10000000; j += i)
                v[j] = 1;
        }
    }
    int n, a, b, maxi = 0, mini = 0, smax = 0;
    cin >> a >> b;
    int poz = a;
    while (v[poz] == 1)
        poz++;
    int prev = poz;
    poz++;
    while (v[poz] == 1 && poz < b)
        poz++;
    if (poz == b && v[b] == 1)
    {
        cout << -1; return 0;
    }
    int next = poz;
    poz++;
    while (poz <= b)
    {
        if (next - prev > smax)
        {
            smax = next - prev;
            maxi = next;
            mini = prev;
        }
        if (v[poz] == 0)
        {
            prev = next;
            next = poz;
        }
        poz++;
    }
    cout << mini << " " << maxi;
    return 0;
} 

i expected 43 with 47

c++
codeblocks
asked on Stack Overflow Mar 25, 2019 by Voicu Mihai • edited Mar 25, 2019 by Alan Birtles

3 Answers

3

In your initialisation loop when i is 46349, i*i is 2,148,229,801, this is larger than fits inside a signed 32-bit integer so evaluates to -2,146,737,495. v[j] then causes the crash.

You should either modify your code to use a larger data type or set the limit for i to sqrt(10000000) rather than 10000000.

answered on Stack Overflow Mar 25, 2019 by Alan Birtles • edited Mar 25, 2019 by Alan Birtles
2

I'm guessing that i*i overflows when i is large, leading to a negative value for j and an access violation on v[j]=1;.

answered on Stack Overflow Mar 25, 2019 by john
0

You have a potential segmentation fault on line v[j]=1; where j may exceed 10000000.

Please check your boundaries.

answered on Stack Overflow Mar 25, 2019 by Byung Kim • edited Mar 25, 2019 by Ayxan Haqverdili

User contributions licensed under CC BY-SA 3.0