본문 바로가기

OJ

[BOJ] 6588 골드바흐의 추측 (JAVA)

https://www.acmicpc.net/problem/6588

 

6588번: 골드바흐의 추측

각 테스트 케이스에 대해서, n = a + b 형태로 출력한다. 이때, a와 b는 홀수 소수이다. 숫자와 연산자는 공백 하나로 구분되어져 있다. 만약, n을 만들 수 있는 방법이 여러 가지라면, b-a가 가장 큰

www.acmicpc.net

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

public class Main {
	
    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        boolean[] notPrime = new boolean[1000001];
        for (int i = 2; i < 1000001; i++) {
            if (!notPrime[i]) {
                for (int j = i * 2; j < 1000001; j += i) {
                    notPrime[j] = true;
                }
            }
        } // sieve of Eratosthenes

        while (true) {

            int N = Integer.parseInt(br.readLine());

            if (N == 0) break;

            int a = 2;

            while (true) {

                // 둘 다 소수면
                if (!notPrime[a] && !notPrime[N - a]) {
                    sb.append(N + " = " + a + " + " + (N - a) + "\n");
                    break;
                }
                // 두 소수의 합으로 N을 나타낼 수가 없는 경우
                else if (N / 2 <= a) {
                    sb.append("Goldbach's conjecture is wrong.\n");
                    break;
                }
                else a++;

            }

        }

        System.out.print(sb);

    }
	
}