sliver__

백준 - 골드바흐의 추측(9020) 본문

CS/알고리즘

백준 - 골드바흐의 추측(9020)

sliver__ 2021. 11. 18. 15:23
728x90

https://www.acmicpc.net/problem/9020

 

9020번: 골드바흐의 추측

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

www.acmicpc.net

 

골드바흐의 추측

 

주어진 짝수 n을 두 소수의 합으로 나타낼 수 있다.

두 소수의 합이 여러개 있을 수 있고 그 차이가 가장 적은 합의 식을 출력하는 문제이다.

 

제출한 코드는 아래와 같습니다.

 

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
#define MAX_VALUE 10010

int arr[MAX_VALUE];

bool compare(pair<int, int>& p1, pair<int, int>& p2)
{
	return (p1.second - p1.first) < (p2.second - p2.first);
}

void getPrime()
{
	arr[1] = 0;
	for (int i = 2; i * i < MAX_VALUE; i++)
	{
		for (int j = i + i; j < MAX_VALUE; j += i)
		{
			if (arr[j] == 1) arr[j] = 0;
		}
	}
}
int main(void)
{
	for (int i = 0; i < MAX_VALUE; i++) arr[i] = 1;
	getPrime();
	vector< pair<int, int>> v;
	int t, n, leftValue;
	cin >> t;
	for (int i = 0; i < t; ++i)
	{
		v.clear();
		cin >> n;
		for (int j = 2; j <= n / 2; ++j)
		{
			if (arr[j] == 1)
			{
				leftValue = n - j;
				if (arr[leftValue] == 1)
				{
					v.push_back({ j,leftValue });
				}
			}
		}
		sort(v.begin(), v.end(), compare);
		cout << v[0].first << " " << v[0].second << endl;
	}
}

 

728x90

'CS > 알고리즘' 카테고리의 다른 글

백준 - 직각삼각형(4153)  (0) 2021.11.18
백준 - 직사각형에서 탈출(1085)  (0) 2021.11.18
백준 - 베르트랑 공준(4948)  (0) 2021.11.18
백준 - 소수 구하기(1929)  (0) 2021.11.18
백준 - 소인수분해(11653)  (0) 2021.11.18
Comments