I have implemented Sieve of Eratosthenes in c++ but the code crashes for input greater than 10^10.Compiler show signal 11(SIGSEV).It's because of the global array bool a[5000000000000000];
.To check odd numbers upto 10^16, I took the array size as (10^16)/2 = 5 * 10^15. How to reduce the space ?
There is an answer for this question How do i reduce the space complexity in Sieve of Eratosthenes to generate prime between a and b? I tried accordingly but my program crashes.Could anybody provide implementation details to fix it ?
#include <bits/stdc++.h>
using namespace std;
long long unsigned n,sqN;
bool a[5000000000000000];
long long int sieve_of_Eratosthenes();
int main()
{
cout<<"Enter upper bound to generate prime upto:"<<endl;
cin>>n;
long long int count = sieve_of_Eratosthenes();
cout<<"Total = "<<count<<endl;
return 0;
}
long long int sieve_of_Eratosthenes()
{
long long unsigned i,j,count = 0;
sqN = (long long unsigned) sqrt(n);
for(i=3; i<=sqN; i+=2)
{
if(a[i/2]==true)
{
continue;
}
for(j = i*i; j<=n; j+=(2*i))
{
a[j/2] = true;
}
}
if(n>=2)
{
count++;
cout<<2<<endl;
}
for(i=3; i<=n; i+=2)
{
if(a[i/2]==false)
{
cout<<i<<endl;
count++;
}
}
return count;
}