728x90
문제
베르트랑 공준은 임의의 자연수 n에 대하여, n보다 크고, 2n보다 작거나 같은 소수는 적어도 하나 존재한다는 내용을 담고 있다.
이 명제는 조제프 베르트랑이 1845년에 추측했고, 파프누티 체비쇼프가 1850년에 증명했다.
예를 들어, 10보다 크고, 20보다 작거나 같은 소수는 4개가 있다. (11, 13, 17, 19) 또, 14보다 크고, 28보다 작거나 같은 소수는 3개가 있다. (17,19, 23)
자연수 n이 주어졌을 때, n보다 크고, 2n보다 작거나 같은 소수의 개수를 구하는 프로그램을 작성하시오.
입력
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 케이스는 n을 포함하는 한 줄로 이루어져 있다.
입력의 마지막에는 0이 주어진다.
출력
각 테스트 케이스에 대해서, n보다 크고, 2n보다 작거나 같은 소수의 개수를 출력한다.
앞의 문제와 동일하게 에라토스테네스의 체를 활용하여 풀었다. 다만 소수를 출력하지 않고 소수의 수를 구해 출력하였다.
또한 입력이 0이어야 프로그램을 종료하기 때문에 while문을 사용하여 입력을 받았다.
package boj0728;
import java.util.Scanner;
public class BOJ_4948_베르트랑공준 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
while (N != 0) {
int[] arr = new int[2 * N + 1];
for (int i = 2; i <= 2 * N; i++)
arr[i] = i;
for (int i = 2; i <= 2 * N; i++) {
if (arr[i] == 0) // 이미 지워진거면 pass
continue;
for (int j = i * 2; j <= 2 * N; j += i)
// i의 배수를 찾아서 지움, 이때 i는 제외
arr[j] = 0;
}
int cnt = 0;
for (int i = N + 1; i <= 2 * N; i++) {
if (arr[i] != 0)
cnt++;
}
System.out.println(cnt);
N = sc.nextInt();
}
}
}
728x90
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 17478 - 재귀함수가 뭔가요? (자바/Java): 재귀 Recursion (0) | 2022.07.29 |
---|---|
[백준] 9020 - 골드바흐의 추측 (자바/Java) (0) | 2022.07.28 |
[백준] 1929 - 소수 구하기 (자바/Java): 에라토스테네스의 체 (0) | 2022.07.28 |
[백준] 2581 - 소수 (자바/Java) (0) | 2022.07.28 |
[백준] 1978 - 소수 찾기 (자바/Java) (0) | 2022.07.28 |