๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 17103_๊ณจ๋“œ๋ฐ”ํ ํŒŒํ‹ฐ์…˜

๋ฟŒ์•ผ._. 2024. 4. 23. 11:52

Silver II

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

< ๊ณจ๋“œ๋ฐ”ํ ํŒŒํ‹ฐ์…˜ >

 

๋ฌธ์ œ ํ’€์ด 

 

์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฏธ๋ฆฌ ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•ด ๋‘”๋‹ค. ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ 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 _17103_ { // ๊ณจ๋“œ๋ฐ”ํ ํŒŒํ‹ฐ์…˜

	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[1000001];
		for (int i = 2; i < 500001; i++) {
			if (!arr[i]) {
				for (int j = i + i; j < 1000001; j += i) {
					arr[j] = true;
				}
			}
		}

		for (int i = 0; i < t; i++) {
			int num = Integer.parseInt(bf.readLine());
			int cnt = 0;

			for (int j = 2; j <= num / 2; j++) {
				if (!arr[j] && !arr[num - j]) {
					cnt += 1;
				}
			}
			bw.write(cnt + "\n");
		}
		bw.flush();
	}
}
๋ณ€์ˆ˜)
t : ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ๊ฐœ์ˆ˜
arr : ์†Œ์ˆ˜ ํŒ๋ณ„
num : ์ž…๋ ฅ๋ฐ›์€ ์ •์ˆ˜
cnt : ๊ณจ๋“œ๋ฐ”ํ ํŒŒํ‹ฐ์…˜์˜ ์ˆ˜

 

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