I have written code to solve the prime generator problem. I am given an input which contains in the first line the number of test cases, and for each test case, I am given a range and I have to print the list of prime numbers in that range. However, it doesn't pass and says that time limit has exceeded. I tried optimizing the code as best as I could, but I couldn't find any further optimization.
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
class Primes {
private static Set<Long> primes = new LinkedHashSet<Long>();
private static long biggestPrime = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfTC = scanner.nextInt();
for (int i = 0; i < numberOfTC; i++) {
long a = scanner.nextInt();
long b = scanner.nextInt();
long startFrom = a;
if (a >= biggestPrime) {
startFrom = biggestPrime;
}
if (biggestPrime == 0) {
startFrom = 2;
}
for (long j = startFrom; j <= b; j++) {
if (isPrime(j) && j >=a) {
System.out.println(j);
}
}
System.out.println();
}
scanner.close();
}
private static boolean isPrime(long x) {
if (x < biggestPrime) {
if (primes.contains(x)) {
return true;
}
return false;
}
for (Long prime : primes)
{
if (prime*prime > x ) {
break;
}
if (x % prime == 0) {
return false;
}
}
if (biggestPrime < x) {
primes.add(x);
biggestPrime = x;
}
return true;
}
}