0

I have written this code for a problem from Codeforces. The code syntax and logic is correct. But the code is not taking any input only. It just runs and terminates on its own. code:

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e7+5;

int main(){
    int seive[maxn];
    int sum[maxn];
    int count[maxn];
    memset(seive,1,sizeof(seive));
    memset(sum,0,sizeof(sum));
    memset(count,0,sizeof(count));
        
    int n,inp;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++) cin>>arr[i];
    for(int i=0;i<n;i++){
        count[arr[i]]+=1;
    }
    for(int i=2;i<maxn;i++){
        if(seive[i]==1){
            for(int j=i;j<maxn;j+=i){
                if(j!=i) seive[j]=0;
                sum[i]+=count[j];
            }
        }
        sum[i] = sum[i-1]+sum[i];
    }
    int m;
    cin>>m;
    while(m--){
        int l,r;
        if(r>10000000) r=10000000;
        if(l>=10000000) cout<<0;
        else cout<<sum[r] - sum[l-1];
        cout<<"\n";
    }
}

Please help me in finding out what is causing this problem.

  • 2
    I'm 99% sure the code can't run because the size of the stack is much less than the buffers you have. Use dynamic memory. Also obligatory don't use `using namespace std;` and `#include `. Yup tested and segfault. The stack has a limited size (10Kb maybe? I can't remember), you can't just allocate any amount of variable there. – Lala5th Aug 22 '21 at 17:36
  • 1
    Does this answer your question? [Getting a stack overflow exception when declaring a large array](https://stackoverflow.com/questions/571945/getting-a-stack-overflow-exception-when-declaring-a-large-array) – Lala5th Aug 22 '21 at 17:40
  • Also, `int arr[n]` is not valid C++ code. It may be an extension in some compilers. Use `std::vector` instead. – Thomas Matthews Aug 22 '21 at 17:49
  • Try moving your large arrays outside of the `main` function. This, global memory space, may have more room than local variable storage. – Thomas Matthews Aug 22 '21 at 17:50
  • Do you really want to do this: `count[arr[i]]+=1;`? It can be problematic with very large numbers. Also, you need to verify that `arr[i]` is within the range of the `count[]` array, before using it as an index. – Thomas Matthews Aug 22 '21 at 17:53
  • @ThomasMatthews I think it might be in this case, as `maxn` is a compile time constant. I don't know how it is handled in this case however – Lala5th Aug 22 '21 at 17:53
  • how to solve this issue the?? – user7186002 Aug 23 '21 at 06:39

0 Answers0