Skip to main content
1 of 5

Prime number generation - SPOJ

It is a program to generate prime numbers for a given range. The sieve of eratosthenes algorithm was implemented, but still the SPOJ says time limit exceeded. Please provide some optimizations. Thank you!

import java.util.*;
import java.lang.*;
class Main
{
    public static void prime(int m, int n)
    {
    boolean arr[] = new boolean[n+1];
    for(int i = 0; i < arr.length; i++)
        arr[i] = true;
    for(int p = 2; p*p <= n; p++)
    {
        if(arr[p] == true)
        {
            for(int j = p*2; j <= n; j += p)
                arr[j] = false;
        }
    }
    for(int i = m; i <= n; i++) 
    { 
        if(arr[i] == true) 
            System.out.print(i + " "); 
    } 
}
public static void main (String[] args) throws java.lang.Exception
{
    Scanner in = new Scanner(System.in);
    int test = in.nextInt();
    int m = 0,n = 0,flag = 0;
    while(test > 0)
    {
        m = in.nextInt();
        n = in.nextInt();
        prime(m,n);
        test--;
    }
}
}