Prime visit problem|| 2 out of 3 test cases failed showing RUN ERROR

import java.util.*;
public class Main {
static final int MAX=10000;
static int prefix[] = new int[MAX + 1];
static void buildPrefix() {
boolean prime[] = new boolean[MAX + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= MAX; p++) {
if (prime[p] == true) {
for (int i = p * 2; i <= MAX; i += p)
prime[i] = false;
}
}
prefix[0] = prefix[1] = 0;
for (int p = 2; p <= MAX; p++) {
prefix[p] = prefix[p - 1];
if (prime[p])
prefix[p]++;
}
}
static int query(int L, int R)
{
return prefix[R] - prefix[L - 1];
}

public static void main(String args[]) {
	Scanner sc=new Scanner(System.in);
	int N=sc.nextInt();
	while(N>0){
		buildPrefix();
		int a=sc.nextInt();
		int b=sc.nextInt();
		System.out.println(query(a,b));
		N--;
	}
	sc.close();
}

}

@Rajput.apry If I say a = 0, then

this will throw array index out of bound and this is what’s happening over here.3
Another thing is, if you are precomputing the primes then precompute over the given constraint which is 10^6. Then simply loop over the range a, b and count the marked primes thats all.

Also call the precompute function only ones why calling for every test case?
It will increase the execution time overhead.

If you have any doubts, lemme know else resolve the doubt!

Two of three test cases are cleared and one is showing TLE!!

import java.util.*; public class Main { static Scanner sc=new Scanner (System.in); public static void main(String args[]) { int N=sc.nextInt(); while(N>0){ int a=sc.nextInt(); int b=sc.nextInt(); N–; int flag=0,count=0; for(int i=a;i<=b;i++){ if(i==0||i==1){ continue; } flag=1; for (int j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } if(flag==1){ count++; } } System.out.println(count); } } }