I have to write script to print prime numbers in given range. Currently I am using the following script:
#include <iostream>
using namespace std;
int main()
{
int n,p,m;
cin>>n >> m;
int * arr;
arr= new int[m+1];
for (int i=0; i<=m; i++)
{
arr[i]=0;
}
for(int i=2;i<=m;i++){
if(arr[i]==0)
{ p=i;
for (int j=2;p*j<=m;j++)
{
arr[p*j]=1;
}
}
}
for(int i=n;i<=m;i++){
if(arr[i]==0)cout<<i<<endl;
}
delete[] arr;
return 0;
}
It works fine for small inputs (it prints 1 as prime but that is easy to fix). However, when I input numbers like 1999998973 and 1999999973 it crashes with bad_alloc
.
I know I probably made a huge array, but I don't know how to fix it. I have tried a different algorithm but it was really slow, I need it to print the numbers within about 2 seconds or so. Does anyone have an idea?