I have doubt in code of Divisible subarrays problem

  1. If I declare ll a[1000005],pre[1000005]; in main, I am getting segmentation error. Why??
  2. Why are we doing sum=(sum+n)%n; for negative numbers and getting the correct answer?

hello @sahilkhan2312000131

when u declare array in function then it get allocated in stack , whereas when we make array global then it is stored in data segment.data segment allow more memory compared to stack that why we see such behaviour.

its a mod property .
when we do sum% n then it gives us number in range [-(n-1)…(n-1)]

so to make it non negative we add n ,and then take its mod.

i would recommend to read about all mod property.

When we make Prime sieve we declare array of the same size inside main and get no error but here we are getting error why?

share that code with me

#include<bits/stdc++.h>
using namespace std;
void abc(int p[]){
for(int i=3;i<=1000000;i+=2){
p[i]=1;
}
for(long long i=3;i<=1000000;i+=2){
if(p[i]==1){
for(long long j=i*i;j<=1000000;j+=i){
p[j]=0;
}
}
}
p[2]=1;
p[1]=p[0]=0;
}
int main() {
int p[1000005]={0};
abc§;
int sum[1000005]={0};
for(int i=1;i<=1000000;i++){
sum[i]=sum[i-1]+p[i];
}
int t; cin>>t;
while(t–){
int a,b;
cin>>a>>b;
cout<<sum[b]-sum[a-1]<<endl;
}
return 0;
}
This is code for Prime visits problem

Replace int with long long and then run

Ok, I got it…Thank you so much

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.