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

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60

3 Answers3

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.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • No, `i*i` is correct for the sieve. When considering multiples of 5, you don't need to consider 5x2, or 5x3 (they will have been eliminated as multiple of 2 and 3), - you start at 5x5. (Point is though, that similarly you don't need to consider values of `i` above sqrt(10million) ). – Martin Bonner supports Monica Mar 25 '19 at 16:40
  • ok, was just going by wikipedia which says to start at 2p in step 3 https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes – Alan Birtles Mar 25 '19 at 16:43
  • Works on my machine. However, I'm using 64-bit int. I think it will fail on machines using 32-bit int. – Eljay Mar 25 '19 at 16:43
  • @Eljay What compiler are you using that has 64-bit *int* ? (64-bit pointers and longs, sure - but int ??!?) – Martin Bonner supports Monica Mar 25 '19 at 16:45
  • @MartinBonner • a modified version of clang. I'm also using separate heaps for `malloc`, `new` and `new[]`. – Eljay Mar 25 '19 at 16:48
  • 2
    64-bit int -- int64_t, include < cstdint > – 2785528 Mar 25 '19 at 17:37
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;.

john
  • 85,011
  • 4
  • 57
  • 81
0

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

Please check your boundaries.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Byung Kim
  • 21
  • 5