UVa 686 Goldbach’s Conjecture II Solution in Java

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Created by dhruv.pancholi on 20/11/16.
 */
public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        InputReader in = new InputReader(System.in);

        int limit = 2 << 14;
        SieveOfEratosthenes soe = new SieveOfEratosthenes(limit);
        List<Integer> primes = soe.getPrimes();
        int[] arr = new int[limit + 1];

        int p1, p2;
        for (int i = 0; i < primes.size(); i++) {
            p1 = primes.get(i);
            for (int j = i; j < primes.size(); j++) {
                p2 = primes.get(j);
                if (p1 + p2 > limit) break;
                arr[p1 + p2]++;
            }
        }

        int n = 0;
        while (true) {
            n = in.nextInt();
            if (n == 0) break;
            System.out.println(arr[n]);
        }
    }

    private static class SieveOfEratosthenes {
        private boolean[] a;

        public SieveOfEratosthenes(int N) {
            a = new boolean[N + 1];
            for (int i = 0; i <= N; i++) {
                a[i] = true;
            }
            a[0] = false;
            a[1] = false;

            int root = (int) Math.sqrt(N);
            for (int i = 2; i <= root; i++) {
                for (int j = 2 * i; j <= N; j += i) {
                    a[j] = false;
                }
            }
        }

        public boolean[] getArray() {
            return a;
        }

        public boolean isPrime(int n) {
            return a[n];
        }

        public List<Integer> getPrimes() {
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 1; i < a.length; i++) {
                if (a[i]) {
                    list.add(i);
                }
            }
            return list;
        }
    }

    public static class InputReader {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

Sample Input:

6
10
12
0

Sample Output:

1
2
1

Leave a comment