๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 11502_์„ธ ๊ฐœ์˜ ์†Œ์ˆ˜ ๋ฌธ์ œ

๋ฟŒ์•ผ._. 2024. 5. 8. 12:01

Silver IV

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

< ์„ธ ๊ฐœ์˜ ์†Œ์ˆ˜ ๋ฌธ์ œ >

 

๋ฌธ์ œ ํ’€์ด 

 

๋ชจ๋“  ์„ธ ์†Œ์ˆ˜๋ฅผ ๋”ํ•ด๋ณด๋ฉฐ ๊ฐ€๋Šฅํ•œ์ง€ ํŒ๋‹จํ•œ๋‹ค.

 

 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 _11502_ { // ์„ธ ๊ฐœ์˜ ์†Œ์ˆ˜ ๋ฌธ์ œ

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

		int t = Integer.parseInt(bf.readLine());

		boolean arr[] = new boolean[1000];
		arr[0] = true;
		arr[1] = true;
		for (int i = 2; i < 501; i++) {
			if (!arr[i]) {
				for (int j = i + i; j < 1000; j += i) {
					arr[j] = true;
				}
			}
		}

		for (int i = 0; i < t; i++) {
			int k = Integer.parseInt(bf.readLine());
			boolean flag = false;

			for (int a = 2; a <= k; a++) {
				if (!arr[a]) {
					for (int b = a; b <= k - a; b++) {
						if (!arr[b]) {
							if (!arr[k - a - b]) {
								bw.write(a + " " + b + " " + (k - a - b) + "\n");
								flag = true;
								break;
							}
						}
					}
					if (flag) {
						break;
					}
				}
			}
			if (!flag) {
				bw.write("0\n");
			}
		}
		bw.flush();
	}
}
๋ณ€์ˆ˜)
t : ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ˆ˜
arr : ์†Œ์ˆ˜ ํŒ๋‹จ
k : ์ •์ˆ˜ 
flag : ์„ธ ์†Œ์ˆ˜์˜ ํ•ฉ์œผ๋กœ ํ‘œํ˜„ ๊ฐ€๋Šฅ ์—ฌ๋ถ€

 

ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ๋จผ์ € 2~999๊นŒ์ง€์˜ ์†Œ์ˆ˜๋ฅผ ํŒ๋‹จํ•˜์—ฌ arr์— ์†Œ์ˆ˜ ์—ฌ๋ถ€๋ฅผ ์ €์žฅํ•œ๋‹ค. ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ˆ˜๋งŒํผ ์ •์ˆ˜ k๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

1) a : 2๋ถ€ํ„ฐ k๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.

2) ๋งŒ์•ฝ a๊ฐ€ ์†Œ์ˆ˜๋ผ๋ฉด b : a๋ถ€ํ„ฐ k-a๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.

3) ๋งŒ์•ฝ b๊ฐ€ ์†Œ์ˆ˜๋ผ๋ฉด k-a-b๊ฐ€ ์†Œ์ˆ˜์ธ์ง€ ํŒ๋‹จํ•œ๋‹ค. k-a-b๊ฐ€ ์†Œ์ˆ˜๋ผ๋ฉด ๊ทธ ๊ฐ’์„ ์ถœ๋ ฅํ•œ ํ›„ ์ข…๋ฃŒํ•œ๋‹ค.

4) ์„ธ ์†Œ์ˆ˜์˜ ํ•ฉ์œผ๋กœ ํ‘œํ˜„๋˜๋Š” ๊ฒƒ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด 0์„ ์ถœ๋ ฅํ•œ๋‹ค.