Problem:
Pair of Primes

We arrange the numbers between 1 and N (1 <= N <= 10000) in increasing
order and decreasing order like this:

1 2 3 4 5 6 7 8 9 . . . N
N . . . 9 8 7 6 5 4 3 2 1

Two numbers faced each other form a pair. Your task is to compute the number of pairs P such that both
numbers in the pairs are prime.

Input

Input contains several test cases. Each test case consists of an integer N in
one line.

Output

For each line of input, output P .

Sample Input

1
4
7
51

Output for the Sample Input

0
2
2
6

Solution in JAVA (judge verdict: Time Limit Exceeded)

import java.io.*;
import java.util.*;

public class Main {

	public static void main(String[] args) {
		BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
		try {
			String line;
			int N;
			
			while((line=r.readLine())!=null){
				N = Integer.parseInt(line);
				ArrayList<Integer> primelist = prime(N);
				
				int count=0;
				
				for(int i=1;i<N;i++){
					if(primelist.contains(i) && primelist.contains(N-i+1)){
						count++;
					}
				}
				
				System.out.println(count);
				
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//Sieve of Eratosthenes
	public static ArrayList<Integer> prime(int n){
		ArrayList<Integer> primes = new ArrayList<Integer>();
		
		Boolean[] p = new Boolean[n+1];
		//initialize boolean array
		for(int i = 0;i<=n;i++){
			p[i] = true;
		}
		int i;
		for(i=2;i<=Math.sqrt(n);i++){
			if(p[i]){
				primes.add(i);
				//exclude multiples
				for(int j=2;i*j<=n;j++){
					p[i*j] = false;
				}
				continue;
			}
		}
		
		for(;i<=n;i++){
			if(p[i]){
				primes.add(i);
			}
		}
		
		return primes;
	}
	
}