4 / 4
Oct 2009

Hi,

I'm trying to solve PRIME1 problem and getting a Wrong Answer when I submit.
Unfortunately the system doesn't tell me which case it fails.

Below is my code.
Can somebody tell me whats wrong with it ?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
    public boolean isPrime(int iNum) {

	if (iNum == 1)
		return false;

	for (int i = 2; i < (iNum / 2 + 1); i++) {
		if (iNum % i == 0) {
			return false;
		}
	}
	return true;
}

public void printPrimes(int iStartNum, int iEndNum) {

	int i = iStartNum;
	while (i <= iEndNum) {
		if (isPrime(i)) {
			System.out.println(i);
		}

		i++;
	}

}

public static void main(String[] args) {

	Main pg = new Main();
	int val = 0;

	try {

		val = Integer.parseInt(new BufferedReader(new InputStreamReader(
				System.in)).readLine());
		int[][] arrInput = new int[val][2];
		BufferedReader in = new BufferedReader(new InputStreamReader(
				System.in));
		String range = "";

		for (int i = 0; i < val; i++) {

			range = in.readLine();

			StringTokenizer st = new StringTokenizer(range);

			arrInput[i][0] = Integer.parseInt(st.nextToken());
			arrInput[i][1] = Integer.parseInt(st.nextToken());

		}

		for (int i = 0; i < val; i++) {

			if ((arrInput[i][0] >= 1) && (arrInput[i][1] <= 1000000000)
					&& (arrInput[i][1] - arrInput[i][0] <= 100000))
				pg.printPrimes(arrInput[i][0], arrInput[i][1]);
			System.out.println();

		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
}
  • created

    Oct '09
  • last reply

    Oct '09
  • 3

    replies

  • 359

    views

  • 2

    users

You seem to be creating an InputStreamReader on System.in twice - I presume that is causing the problem.

You seem to be doing a few other strange things in your code as well - eg the if condition in main is completely unnecessary as you are guaranteed the input will lie within those bounds. And there is no need to store all of the input in an array before processing it - that will suffice here but in some problems that will cause you to exceed the memory limit, so it's not advisable.

Anyway, if you've tested your code on the largest possible input file (10 cases of the largest size), you'll know this approach won't fit inside the time limit anyway, so you'll need to think of an improved algorithm.

Thanks for the reply. Indeed that seems to be the problem.
I will try and improve the code to be accepted.

Is the time limit dynamic to the problem ? If so how do I know what the limit is ?

The time limit is mentioned at the bottom of the problem - you have 6 seconds to complete each input file, which could have 10 cases in it. (That's 6 seconds on the judge, which is often quite a bit slower than a home computer due to the specs).

Suggested Topics

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