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의 골드바흐 파티션을 출력한다. 출력하는 소수는 작은 것부터 먼저 출력하며, 공백으로 구분한다.
3
8
10
16
3 5
5 5
5 11
M
을 구한다.M
보다 작은 모든 소수를 구한다.(에라토스 테네스의 채)// 시간 : 1324ms
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
bool what_is_decimals[10001];
vector<int> decimals;
void guess(int number){
int minA = 0, minB = 20000;
for (int i = 0; i < decimals.size(); i++){
if (decimals[i] > number) break;
for (int j = 0; j < decimals.size(); j++){
if (decimals[j] > number) break;
else if (decimals[i] + decimals[j] > number) break;
else if (number == decimals[i] + decimals[j]){
if (max(minA, minB) - min(minA, minB) >
max(decimals[i], decimals[j]) - min(decimals[i], decimals[j])){
minA = decimals[i];
minB = decimals[j];
}
}
}
}
cout << min(minA, minB) << ' ' << max(minA, minB) << endl;
}
// 에라토스 테네스의 체
// 출처 : https://marobiana.tistory.com/91
void find_decimals(int max_number){
// 소수 구하기
for (int i = 2; i < sqrt(max_number); i++){
if (what_is_decimals[i]) continue;
for (int j = i + i; j < max_number; j += i)
if (!what_is_decimals[j]) {
what_is_decimals[j] = true;
}
}
for (int i = 2; i < max_number; i++){
if (!what_is_decimals[i]) decimals.push_back(i);
}
}
int main(){
// 추가후 1236ms
// ---
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL); // 추가후 1252ms
// ---
int T;
int input_data;
cin >> T;
find_decimals(10000);
for (int i = 0; i < T; i++){
cin >> input_data;
guess(input_data);
}
return 0;
}
1236ms, 다시 한번 풀어야겠다.