1 / 2
Apr 2013

Hello, why does this code give me a runtime error but works fine on my pc?
I tried to run it with a lower BitSet size that gets all primes till 10^8 only, and when I do that I get time limit exceeded.
Is it possible to adjust this code to make it work correctly on spoj?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.BitSet;
public class Main
{
    public static void main(String[]args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int i=0;
		int largest=0;
		int[]a=new int[10];
		int[]b=new int[10];
		StringTokenizer t = new StringTokenizer(br.readLine());;
		int n = Integer.parseInt(t.nextToken());
		for(i=0;i<n;i++) //gets the 2 integers of every test case
		{
			t = new StringTokenizer (br.readLine());
			a[i]=Integer.parseInt(t.nextToken());
			b[i]=Integer.parseInt(t.nextToken());
		}
		BitSet notPrime = new BitSet (1000000001);
		notPrime.set(1);
		for(int j=2;j<=31622;j++) //finds all the non-Primes in the range 1 -> 10^9, 31622 is the square root of 10^9
		{
			if(!(notPrime.get(j)==true))
			{
				for(int k = j*2;k<=1000000000;k+=j)
				{
					notPrime.set(k);
				}
			}
		}
		for(int j=0;j<i;j++) //Print all primes in the range of every case
		{
			for(int k=a[j];k<=b[j];k++)
			if(!(notPrime.get(k)==true))System.out.println(k);
			System.out.println();
		}
    }
}
  • created

    Apr '13
  • last reply

    Apr '13
  • 1

    reply

  • 342

    views

  • 2

    users

Does the list of primes change for each test case? You don't even want to store all of the primes up to 10^8. Focus on what you actually need to determine if a number is prime.

Suggested Topics

Want to read more? Browse other topics in JAVA based languages or view latest topics.