# Prime1:Logical Error in the code

https://www.codechef.com/problems/PRIME1

My code is just crashing before entering any data.

``````   #include<iostream>
#include<cmath>
#define y 10000000
using namespace std;

int main()
{
int t,x,j,i=0;
cin>>t;
int m,n;
int primes[y];
int prime[100000];
for(i=0;i<=sqrt(y);i++)
primes[i]=1;
primes[0]=0;
primes[1]=0;
for(i=2;i<=sqrt(y);i++)
{
if(primes[i]==1)
{
for(j=2;i*j<=sqrt(y);j++)
primes[i*j]=0;
}
}
while(t--)
{
cin>>m >>n;

i=2;
while(primes[i]==1)
{
x=(m/i)*i;
for(j=x;j<=n;j=j+i)
{
prime[j]=0;
}
for(j=m;j<=n;j++)
{
if(prime[j]==1)
cout<<j;
}
cout<<"\n";
i++;
}
}

return 0;
}``````

#define y 10000000

your y is too big i guess

In the declaration portion, #define y 10000000, the constant that is declared must be in the range of and int data type. You have to use #define y 100000 or rather use a long long int type of variable in the main() and use it.

But listen primes[y] will again crash as it is beyond the maximum allocated size. So try another solution!

Happy Coding

It is correct that y is “too large”. The problem yout encounter is caused by trying to allocate a huge mount of memory on the stack (the place the local variables are stored) in the statement

`````` int primes[y];
``````

Memory allocation on the stack is typically limited to a few MB, that is to a few 100000 ints. Almost all the memory you can use (hundreds of MB) is accessible on the heap.
There are two remedies for this:

1. Use a global array instead: Define primes out of the main function

2. Use vector from the STL. While it has a small penalty in terms of speed (totally neglible for a one-time allocation as in this case) you can use for example a dynamically growing size of the vector.
In this case

vector primes(y,1);

will additionally take care of the initialization with the value 1 in all components.

One more thing: Don’t #define a short word like y, especially as a beginner. Use some longer name and use const int instead. Otherwise it will probably bite you someday.

the constant is still in the range of int data type. isn’t INT_MAX = 2147483647?

//