I am working on a program which prints the number of pairs of prime numbers (within a range L and R) whose difference is 6, where 2 <= L < R <= 10^9.
eg.,
L=2 R=20
Ans: 4
Explanation: 4 pairs are there: {5, 11}, {7, 13}, {11, 17}, {13, 19}
So my approach is to first store all the prime numbers within the range and then find all the pairs.
In worst case, L=2 and R=10^9; To get all the prime numbers I am using sieve of eratosthenes, but its time complexity is O(nloglogn) which is a problem and another problem is of space (space complexity is O(n)) [array of size 10^9 can not be there]. I am running this program over online IDE.
#include <bits/stdc++.h>
#define siz 1000000000
using namespace std;
int main()
{
vector<bool> prime(siz);
int i, j;
for(i=0;i<siz;i++)
{
prime[i]=false;
}
for(i=2;i*i<=siz;i++)
{
if(prime[i]==false)
{
for(j=i*i;j<=siz;j+=i)
{
prime[j]=true;
}
}
}
int ans=0;
for(i=0;i<siz;i++)
{
if(prime[i]==false)
{
ans++;
}
}
cout<<ans;
return 0;
}
Above program is a part of the whole program where I am just counting the number of prime numbers till 10^9 and the message by compiler is SIGTSTP and when I am reducing the siz to 10^8, it's running fine and the output is 5761455 which is correct (I have verified it from wikipedia).