Prime Numbers in Range (Segmented Sieve of Eratosthenes)
Prime Numbers in Range (Segmented Sieve of Eratosthenes)
Segmented Sieve is used for finding prime numbers in the given range (low and high) with less auxiliary space . The problem with simple Sieve of Eratosthenes is that it takes more memory for given long ranges (low and high).
PROBLEM STATEMENT :
SOLUTION :
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char** argv)
{
int t;
cin>>t;
while(t--)
{
int low,high,i,j,s;
vector<int> prime;
cin>>low>>high;
s=(int)sqrt(high);
bool hashPrime[s+1];
memset(hashPrime,true,sizeof(hashPrime));
bool res[high-low+1];
memset(res,true,sizeof(res));
for(i=2;i<=s;++i)
{
if(hashPrime[i]==true)
{
prime.push_back(i);
for(j=i*i;j<=s;j+=i)
{
hashPrime[j]=false;
}
}
}
for(int i:prime)
{
int l=floor(low/i)*i;
if(l<low) l+=i;
if(l==i) l+=i;
for(j=l;j<=high;j+=i)
{
res[j-low]=0;
}
}
for(i=0;i<=high-low;++i)
{
if(res[i]==1&&i+low!=1)
{
cout<<i+low<<"\n";
}
}
cout<<"\n";
}
return 0;
}
For Segmented Sieve, Auxiliary Space : O(√n)
For Normal Sieve, Auxiliary Space : O(n)
Comments
Post a Comment