delpho

[Silver II] 골드바흐의 추측 - 9020 (소수, 생각해보지못한 풀이..!) 본문

알고리즘/소수

[Silver II] 골드바흐의 추측 - 9020 (소수, 생각해보지못한 풀이..!)

delpho 2023. 2. 1. 17:26

문제 링크

성능 요약

메모리: 229620 KB, 시간: 4100 ms

분류

수학(math), 정수론(number_theory), 소수 판정(primality_test), 에라토스테네스의 체(sieve)

문제 설명

1보다 큰 자연수 중에서 1과 자기 자신을 제외한 약수가 없는 자연수를 소수라고 한다. 예를 들어, 5는 1과 5를 제외한 약수가 없기 때문에 소수이다. 하지만, 6은 6 = 2 × 3 이기 때문에 소수가 아니다.

골드바흐의 추측은 유명한 정수론의 미해결 문제로, 2보다 큰 모든 짝수는 두 소수의 합으로 나타낼 수 있다는 것이다. 이러한 수를 골드바흐 수라고 한다. 또, 짝수를 두 소수의 합으로 나타내는 표현을 그 수의 골드바흐 파티션이라고 한다. 예를 들면, 4 = 2 + 2, 6 = 3 + 3, 8 = 3 + 5, 10 = 5 + 5, 12 = 5 + 7, 14 = 3 + 11, 14 = 7 + 7이다. 10000보다 작거나 같은 모든 짝수 n에 대한 골드바흐 파티션은 존재한다.

2보다 큰 짝수 n이 주어졌을 때, n의 골드바흐 파티션을 출력하는 프로그램을 작성하시오. 만약 가능한 n의 골드바흐 파티션이 여러 가지인 경우에는 두 소수의 차이가 가장 작은 것을 출력한다.

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있고 짝수 n이 주어진다.

출력

각 테스트 케이스에 대해서 주어진 n의 골드바흐 파티션을 출력한다. 출력하는 소수는 작은 것부터 먼저 출력하며, 공백으로 구분한다.





문제 풀이 리뷰

  1. 소수를 구해야하니 에라토스테네스의 체 코드를 사용해야겠다고 생각했다.
  2. 골드바흐 파티션을 구하는 부분은 에라토스테네스의 체로 구한 소수 배열을 ArrayList에 저장 후 comparable을 상속한 class을 활용하여 구하면 되겠다라고 생각했다.
  3. 이 두개의 생각을 가지고 구현을 했는데, 메모리양이랑 시간이 되게 높게 나왔다….
  1. 그래서 다른 방법이 있나 구글링을 해보았더니, 주어진 수 기준으로 -1, +1씩 해가며 골드바흐 파티션을 구한다고 했다. (이 원리가 소수의 특성중 하나인건지는 잘 모르겠다…. 알고싶다 ㅠㅠ)
출처 : [https://st-lab.tistory.com/91](https://st-lab.tistory.com/91)

제출 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

        for (int i = 0; i < T; i++) {
            int number = Integer.parseInt(br.readLine());

            ArrayList<Integer> primes = getPrime(number);
            ArrayList<Partition> partitions = findPartition(primes, number);
            Collections.sort(partitions);
            System.out.println(partitions.get(0).num1 + " " + partitions.get(0).num2);
        }

    }

    private static ArrayList<Partition> findPartition(ArrayList<Integer> primes, int number) {
        Collections.reverse(primes);

        ArrayList<Partition> partitions = new ArrayList<>();

        for (int i = 0; i < primes.size(); i++) {
            for (int j = i + 1; j < primes.size(); j++) {
                if (primes.get(i) + primes.get(j) == number) {
                    partitions.add(new Partition(primes.get(i),primes.get(j)));
                }
            }
            if (primes.get(i) + primes.get(i) == number) {
                partitions.add(new Partition(primes.get(i),primes.get(i)));
            }
        }

        return partitions;

    }

    private static ArrayList<Integer> getPrime(int number) {
        int[] arr = new int[number + 1];

        for (int i = 2; i <= number; i++) {
            arr[i] = i;
        }

        for (int i = 2; i <= number; i++) {
            for (int j = i + i; j <= number; j += i) {
                if (arr[j] == 0) continue;
                arr[j] = 0;
            }
        }

        ArrayList<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= number; i++) {
            if (arr[i] != 0) {
                primes.add(arr[i]);
            }
        }

        return primes;
    }

    public static class Partition implements Comparable<Partition>{
        int num1;
        int num2;

        Partition(int num1, int num2){
            if(num1 < num2){
                this.num1 = num1;
                this.num2 = num2;
            }else{
                this.num1 = num2;
                this.num2 = num1;

            }

        }

        @Override
        public int compareTo(Partition o) {
            return Math.abs(this.num1 - this.num2) - Math.abs(o.num1 - o.num2) ;
        }

    }

}