[BaekJoon] 17103번 - 골드바흐 파티션 [Java][C++]
[BaekJoon] 17103번 - 골드바흐 파티션 [Java][C++]
1. 문제 풀이
짝수 $N$ 에 대해 두 소수의 합으로 나타낼 수 있는 경우의 수를 구하는 문제로 에라토스테네스의 체를 활용해서 $N$ 보다 작은 소수들을 미리 판정해놓으면 간단하게 해결할 수 있다. $2$ 부터 $N / 2$ 까지 탐색하면 순서가 뒤집힌 경우를 세지 않으면서 탐색량도 줄일 수 있다.
2. 코드
1. 풀이 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.io.*;
import java.util.*;
public class Main {
static final int MAX = 1_000_000;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
boolean[] isPrime = sieve();
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
int cnt = 0;
for (int i = 2; i <= n / 2; i++) {
if (isPrime[i] && isPrime[n - i]) cnt++;
}
sb.append(cnt).append("\n");
}
System.out.print(sb);
}
static boolean[] sieve() {
boolean[] isPrime = new boolean[1 + MAX];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= MAX; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= MAX; j += i) {
isPrime[j] = false;
}
}
}
return isPrime;
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000000;
bool isPrime[1 + MAX];
void sieve() {
fill(isPrime, isPrime + MAX + 1, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= MAX; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= MAX; j += i) {
isPrime[j] = false;
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
sieve();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int cnt = 0;
for (int i = 2; i <= n / 2; i++) {
if (isPrime[i] && isPrime[n - i]) cnt++;
}
cout << cnt << '\n';
}
}
This post is licensed under CC BY 4.0 by the author.