Pages

Friday 28 September 2012

UVA - 686 - Goldbach's Conjecture (II)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer("");
        boolean notPrime[]=sievePrime(100*1000);
        while (true) {
            int x = Integer.parseInt(br.readLine());
            int counter=0;
            if(x==0)
                break;
            int i=1,j=x-1;
            while(true){
                if(i>j)
                    break;
                while(notPrime[i]){
                    i++;
                }
                while(notPrime[j]){
                    j--;
                }
                if(i>j)
                    break;
               
                if(i+j==x){
                   counter++;
                   j--;
                   i++;
                }
                else if(i+j>x){
                  j--;
                }
                else if(i+j<x){
                  i++;
                }
            }
            sb.append(counter).append("\n");
        }
        System.out.print(sb);
    }

static boolean [] sievePrime(int x){
        boolean[] notPrime = new boolean[x + 1];
        notPrime[0]=true;
        notPrime[1]=true;
        for (int i = 2; i*i < x+1; i++) {
            if (!notPrime[i]) {
                for (int j = i; i*j < x+1; j++) {
                    notPrime[i*j] = true;
                }
            }
        }
        return notPrime;
    }

}

No comments:

Post a Comment