๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 1418_K-์„ธ์ค€์ˆ˜

๋ฟŒ์•ผ._. 2024. 4. 26. 14:28

Silver V

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

< K-์„ธ์ค€์ˆ˜ >

 

๋ฌธ์ œ ํ’€์ด 

 

์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฏธ๋ฆฌ ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•ด ๋‘”๋‹ค. n์ดํ•˜์˜ ๊ฐ’์„ ๊ฐ๊ฐ ์†Œ์ธ์ˆ˜๋ฅผ ๊ตฌํ•œ ํ›„ ์ตœ๋Œ€ ์†Œ์ธ์ˆ˜ ๊ฐ’์ด k๋ณด๋‹ค ์ž‘์€์ง€ ํŒ๋‹จํ•œ๋‹ค.

 

 my solution (Java)

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

public class _1418_ { // K-์„ธ์ค€์ˆ˜

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

		int n = Integer.parseInt(bf.readLine());
		int k = Integer.parseInt(bf.readLine());

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

		int cnt = 1;
		for (int i = 2; i <= n; i++) {
			if (arr[i]) {
				int temp = 2;
				int num = i;
				int max = -1;
				while (true) {
					if (num % temp == 0) {
						num /= temp;
						max = Math.max(max, temp);
					} else {
						temp++;
					}
					if (temp > num || !arr[num]) {
						max = Math.max(max, num);
						break;
					}
				}
				if (max <= k) {
					cnt += 1;
				}
			} else {
				if (i <= k) {
					cnt += 1;
				}
			}
		}
		System.out.println(cnt);
	}
}
๋ณ€์ˆ˜)
n, k : ์ž์—ฐ์ˆ˜, ์ตœ๋Œ“๊ฐ’ 
arr : ์†Œ์ˆ˜ ํŒ๋ณ„
cnt : k-์„ธ์ค€์ˆ˜ ๊ฐœ์ˆ˜
temp, num, max : ๋‚˜๋ˆ„๋Š” ์ˆ˜, ํ˜„์žฌ ๊ฐ’, ์†Œ์ธ์ˆ˜ ์ตœ๋Œ“๊ฐ’

 

n๊ณผ k๊ฐ’์„ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ 100000๊นŒ์ง€ ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•œ๋‹ค. 1์€ ์ •๋‹ต์— ํฌํ•จํ•ด์•ผ ํ•˜๋ฏ€๋กœ cnt๋ฅผ 1๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค. 2๋ถ€ํ„ฐ n์ดํ•˜๊ฐ’๊นŒ์ง€ ์ˆœํ™˜ํ•˜๋ฉฐ ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

1) ๊ฐ’์ด ์†Œ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด

1-1) temp๋กœ ๋‚˜๋ˆ ์ค€๋‹ค. temp๋กœ ๋‚˜๋ˆ ์ง„๋‹ค๋ฉด temp๊ฐ€ ์†Œ์ธ์ˆ˜ ์ด๋ฏ€๋กœ ๊ฐ’์„ ๋‚˜๋ˆ„๊ณ  ์†Œ์ธ์ˆ˜ ์ค‘์—์„œ ์ตœ๋Œ“๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•œ๋‹ค. ๋‚˜๋ˆ ์ง€์ง€ ์•Š๋Š”๋‹ค๋ฉด temp๊ฐ’์„ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค. ๋งŒ์•ฝ temp๊ฐ€ ํ˜„์žฌ ๊ฐ’๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ํ˜„์žฌ ๊ฐ’์ด ์†Œ์ˆ˜๋ผ๋ฉด ๋” ์ด์ƒ ๊ณ„์‚ฐํ•  ํ•„์š” ์—†์œผ๋ฏ€๋กœ ์†Œ์ธ์ˆ˜ ์ค‘์—์„œ ์ตœ๋Œ“๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•œ ํ›„ ์ข…๋ฃŒํ•œ๋‹ค. ์†Œ์ธ์ˆ˜ ์ค‘์—์„œ ์ตœ๋Œ“๊ฐ’์ด k์ดํ•˜๋ผ๋ฉด cnt๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

2) ๊ฐ’์ด ์†Œ์ˆ˜๋ผ๋ฉด

2-1) ํ˜„์žฌ ๊ฐ’์ด k์ดํ•˜๋ผ๋ฉด cnt๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

 

์ตœ์ข… cnt๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.