Prime visit question

i am getting time limit exceeded in my code for one test case…

heres my code----

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

int func(int x){
if(x==2)
return 1;
else if(x==1||x%2==0)
return 0;
for(int i=3;i*i<=x;i+=2)
if(x%i==0)
return 0;

return 1;

}

int main(){

int t,a,b;

cin>>t;
while(t--){
    cin>>a>>b;
    int flag;
    int counter=0;
    for(int i=a;i<=b;i++){
        flag=func(i);
        if(flag){
        counter++;
       // cout<<i<<endl;
        }
    }
    cout<<counter<<endl;

}

return 0;

}

as constraint are large and go upto 10^9 so u will get tle as tl=1sec ans u are doing it in o(n)
try to use memoization.

1 Like