백준 - 베르트랑 공준[java]

문제 출처: https://www.acmicpc.net/problem/4948

문제 설명

베르트랑 공준은 임의의 자연수 n에 대하여, n보다 크고, 2n보다 작거나 같은 소수는 적어도 하나 존재한다는 내용을 담고 있다.

이 명제는 조제프 베르트랑이 1845년에 추측했고, 파프누티 체비쇼프가 1850년에 증명했다.

예를 들어, 10보다 크고, 20보다 작거나 같은 소수는 4개가 있다. (11, 13, 17, 19) 또, 14보다 크고, 28보다 작거나 같은 소수는 3개가 있다. (17,19, 23)

자연수 n이 주어졌을 때, n보다 크고, 2n보다 작거나 같은 소수의 개수를 구하는 프로그램을 작성하시오.

입력

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 케이스는 n을 포함하는 한 줄로 이루어져 있다.

입력의 마지막에는 0이 주어진다.

1
10
13
100
1000
10000
100000
0

출력

각 테스트 케이스에 대해서, n보다 크고, 2n보다 작거나 같은 소수의 개수를 출력한다.

1
4
3
21
135
1033
8392

문제 풀이

import java.io.*;

public class Main {
    public static void main(String args []) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int num = Integer.parseInt(br.readLine());
        while(num != 0) {
            int count = 0;
            int endPoint = (int) Math.sqrt(2 * num) + 1;
            for(int i = num + 1; i <= 2 * num; i++) {
                if(i != 1 && i != 2 && i != 3 && i != 5 && i != 7) {
                  boolean isPrime = true;
                  for(int j = 2; j <= endPoint; j++) {
                      if(i % j == 0) {
                          isPrime = false;
                          break;
                      }
                  }
                  if(isPrime)
                      count++;
                } else {
                    count++;
                }
            }
            bw.write(count + "\n");
            num = Integer.parseInt(br.readLine());
        }
        bw.flush();
        br.close();
        bw.close();
    }
}

에라토스테네스의 체라는 정수론을 이용하여 소수를 찾아내었다 [에라토스테네스의 체]

찾으려는 정수의 범위의 square root 값까지의 소수로 나뉘어 떨어지는 찾으려는 범위의 모든 정수를 제거하고 남은 수는 모두 소수이다.

다른 풀이

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

public class Main {

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		ArrayList<Integer> n = new ArrayList<>();
		int max = Integer.MIN_VALUE;
		while(true) {
			int N = Integer.parseInt(br.readLine());
			if(N == 0) break;
			n.add(N);
			max = Math.max(max, N);
		}
		
		boolean[] prime = new boolean[(max * 2) + 1];
		prime[1] = true;
		for(int i = 2; i <= Math.sqrt(max * 2); i++) {
			if(prime[i]) continue;
			for(int j = i + i; j <= (max * 2); j += i) {
				prime[j] = true;
			}
		}
		
		int[] cnt = new int[(max * 2) + 1];
		for(int i = 2; i <= (max * 2); i++) {
			cnt[i] = cnt[i-1] + ((prime[i]) ? 0 : 1);
		}
		
		StringBuilder sb = new StringBuilder();
		for(Integer i : n) {
			sb.append((cnt[2*i] - cnt[i]) + "\n");
		}
		System.out.println(sb);
	}

}

내 코드보다 10배 빠른 코드라 한번 분석해보려고 가져왔다.

3개의 for loop은 정말 대단한거 같다.

		for(int i = 2; i <= Math.sqrt(max * 2); i++) {
			if(prime[i]) continue;
			for(int j = i + i; j <= (max * 2); j += i) {
				prime[j] = true;
			}
		}

boolean array로 범위안의 소수를 다 걸러낸다.

		int[] cnt = new int[(max * 2) + 1];
		for(int i = 2; i <= (max * 2); i++) {
			cnt[i] = cnt[i-1] + ((prime[i]) ? 0 : 1);
		}

array를 만들고 누적으로 범위안의 총 소수의 갯수 더해간다.

		StringBuilder sb = new StringBuilder();
		for(Integer i : n) {
			sb.append((cnt[2*i] - cnt[i]) + "\n");
		}

마지막 까지 깔끔하게 StringBuilder로 출력 처리 퍼펙트

좋은 웹페이지 즐겨찾기