This doubt is regarding prime visits question in hackerblocks

my only one test case is passing … sir pls tell whats the error in code

#include
using namespace std;
int isPrime(int a,int b){

	int ans=0;
	
	for(int j=a;j<=b;j++){
		int count=0;
		
		if(j==1){
			count++;
		}
		if(j==2){
			count=0;
		}
		for(int k=2;k<j;k++){
			if(j>2 && j%k==0){
			     count++;					
			}
		}
		if(count==0){
			ans++;
		}
  }
return ans;		

}

int main(){
int t;
cin>>t;

int ans_arr[1000];
for(int i=0;i<t;i++){
	int a,b;
	cin>>a>>b;

	int p=isPrime(a,b);
	ans_arr[i]=p;
}

for(int i=0;i<t;i++){
	cout<<ans_arr[i]<<endl;
}

return 0;
}

hi @Vaibhav277
logic is right
but time complexity of your code is large
and constraints are large and also there are multiple test cases
so you method give definately give TLE
to avoid that

use Seive(https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to build prime array which contains all primes nos from 1 to 1000000

now in every test case just iterate through a to b and count prime nos

i hope you understand

ok sir… let me try that

sir cant understand that… can u make changes in my code and share it with me

hi @Vaibhav277
this is modified code will all required changes

thank you sir…but i see u have used vectors in it which i haven’t studied till now

1 Like