Count k primes time limit error

Hello there,
I m solving Count K-Prime problem and i used sieve of eratosthenes but still it is showing time limit exceed. Following is my cpp code. Please help me.
thank you.

#include
using namespace std;
void countKPrimes(int a, int b, int k){
int MAX = b+1;
int result = 0;
int arr[MAX] = {0};
for(int i=2;i<MAX;i++)
{
if(arr[i]==0)
{
for(int j=i;j<MAX;j+=i)
{
arr[j]++;
}

    }
}
for(int i=a;i<=b;i++)
{
    if(arr[i]==k)
    result++;
}


cout<<result<<endl;

}
int main()
{

int t;
cin>>t;
while(t--)
{
int a,b,k;
cin>>a>>b>>k;
countKPrimes(a,b,k);
}

}

I would suggest do sieve only one time for the maximum value of b. Now, for each tc count the no of primes. You can optimise this also. You can have frequency array for counting no of primes till the given value. Now for each a and b , your answer will be freq[b]-freq[a].
You should share question link also.

2 Likes

hello sebasian,
Thank you very much for reply me, You solvem my problem.
Thanks again