๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 6588_๊ณจ๋“œ๋ฐ”ํ์˜ ์ถ”์ธก

๋ฟŒ์•ผ._. 2024. 4. 24. 22:24

Silver I

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/6588)

< ๊ณจ๋“œ๋ฐ”ํ์˜ ์ถ”์ธก >

 

๋ฌธ์ œ ํ’€์ด 

 

์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฏธ๋ฆฌ ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•ด ๋‘”๋‹ค. ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ 2๋ถ€ํ„ฐ (์ž…๋ ฅ๋ฐ›์€ ์ˆ˜/2)๊นŒ์ง€ ํƒ์ƒ‰ํ•˜์—ฌ ์†Œ์ˆ˜์˜ ํ•ฉ์œผ๋กœ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class _6588_ { // ๊ณจ๋“œ๋ฐ”ํ์˜ ์ถ”์ธก

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

		boolean arr[] = new boolean[1000001];
		for (int i = 2; i <= 500001; i++) {
			if (!arr[i]) {
				for (int j = i + i; j < 1000001; j += i) {
					arr[j] = true;
				}
			}
		}

		int num = 0;
		while ((num = (Integer.parseInt(bf.readLine()))) != 0) {
			int x = 0, y = 0;
			for (int i = 2; i <= num / 2; i++) {
				if (!arr[i] && !arr[num - i]) {
					x = i;
					y = num - i;
					break;
				}
			}
			if (x != 0 && y != 0) {
				bw.write(num + " = " + x + " + " + y + "\n");
			} else {
				bw.write("Goldbach's conjecture is wrong.\n");
			}
		}
		bw.flush();
	}
}
๋ณ€์ˆ˜)
arr : ์†Œ์ˆ˜ ํŒ๋ณ„
num : ์ž…๋ ฅ๋ฐ›์€ ๊ฐ’
x, y : num์„ ์ด๋ฃจ๋Š” ๊ฐ’

 

์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ 1000000๊นŒ์ง€ ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•œ๋‹ค. 0์ด ์•„๋‹ ๋•Œ๊นŒ์ง€ ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. 2๋ถ€ํ„ฐ (์ •์ˆ˜/2)๊นŒ์ง€ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ์†Œ์ˆ˜์˜ ํ•ฉ์œผ๋กœ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋Š”์ง€ ํŒ๋ณ„ํ•œ๋‹ค. b-a๊ฐ€ ๊ฐ€์žฅ ํฐ ๊ฒƒ์„ ์ถœ๋ ฅํ•˜๋ผ๊ณ  ํ–ˆ์œผ๋ฏ€๋กœ 2๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ๊ฐ’์„ ์ฐพ์œผ๋ฉด ๋ฐ”๋กœ ์ข…๋ฃŒํ•˜๋ฉด ๋œ๋‹ค. ๋งŒ์•ฝ 10์„ ์ฐพ๋Š”๋ฐ 3+7, 5+5 ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค๋ฉด 3+7์ด b-a๊ฐ€ ํฐ ๊ฐ’์ด๋‹ค. b-a๊ฐ’์ด ํฌ๋ ค๋ฉด ์ž‘์€ ๊ฐ’๋ถ€ํ„ฐ ํŒ๋ณ„ํ•˜๋ฉด ๋œ๋‹ค. ๋‘ ํ™€์ˆ˜ ์†Œ์ˆ˜์˜ ํ•ฉ์œผ๋กœ ๊ฐ’์„ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ค๋ฉด ๊ฐ’์„ ์ถœ๋ ฅํ•˜๊ณ , ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์—†๋‹ค๋ฉด "Goldbach's conjecture is wrong."์„ ์ถœ๋ ฅํ•œ๋‹ค.