Prime Generator Time limit Exceeds

import java.util.Scanner;

public class PrimeNumber {

static boolean isPrime(int i)
{
	int j;
	for(j=2;j*j<i;j+=2)
	{
		if(i%j == 0)
			return false;
	}
	return true;
}
public static void main(String[] args) {
	
	Scanner scan = new Scanner(System.in);
	int t = scan.nextInt();
	
	while(t!=0)
	{
		int m = scan.nextInt();
		int n = scan.nextInt();
		int i;
		
		for(i=m;i<n+1;i+=2)
		{
			if(isPrime(i))
			{
				System.out.println(i);
			}
		}
	   t--;
	}

	scan.close();
}

}

This is my Java code for prime number generator. How can I improve this code to decrease the time limit and memory?

Instead of nested loops, use Sieve of Eratosthenes . That is the best method to find primes, if the numbers are guaranteed to be less than 10^7 .

Also, Scanner is slower in taking input. Try to use bufferedeader class if input is large.

1 Like