๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 6219_์†Œ์ˆ˜์˜ ์ž๊ฒฉ

๋ฟŒ์•ผ._. 2024. 3. 21. 17:42

Silver III

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

< ์†Œ์ˆ˜์˜ ์ž๊ฒฉ >

 

๋ฌธ์ œ ํ’€์ด 

 

์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜์—ฌ B๊นŒ์ง€์˜ ์†Œ์ˆ˜๋ฅผ ๋ฏธ๋ฆฌ ๊ตฌํ•œ๋‹ค. A์ด์ƒ B์ดํ•˜์˜ ์†Œ์ˆ˜ ์ค‘์—์„œ ์ˆซ์ž D๋ฅผ ํฌํ•จํ•˜๋Š” ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค.

 

 my solution (Java)

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

public class _6219_ { // ์†Œ์ˆ˜์˜ ์ž๊ฒฉ

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

		int a = Integer.parseInt(st.nextToken());
		int b = Integer.parseInt(st.nextToken());
		int d = Integer.parseInt(st.nextToken());

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

		int result = 0;
		String find=Integer.toString(d);
		for (int i = a; i <= b; i++) {
			if (!arr[i]) {
				String str = Integer.toString(i);
				if(str.contains(find)) {
					result+=1;
				}
			}
		}
		System.out.println(result);
	}
}
๋ณ€์ˆ˜)
a, b, d : ๋ฒ”์œ„ A, B, ์ˆซ์ž D
arr : ์†Œ์ˆ˜ ํŒ๋‹จ
result : ์ฃผ์–ด์ง„ ๋ฒ”์œ„ ๋‚ด์—์„œ ์ˆซ์ž D๋ฅผ ํฌํ•จํ•˜๋Š” ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜
find : ์ˆซ์ž D -> ๋ฌธ์ž์—ด D

 

๋ฒ”์œ„ A, B์™€ ์ˆซ์ž D๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜์—ฌ 0๋ถ€ํ„ฐ B๊นŒ์ง€ ์†Œ์ˆ˜๋ฅผ ๋ฏธ๋ฆฌ ๊ตฌํ•œ๋‹ค. contains ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์ˆซ์ž D๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พผ๋‹ค. A์ด์ƒ B์ดํ•˜ ๊ฐ’ ์ค‘์—์„œ ์†Œ์ˆ˜์ธ ๊ฒƒ์„ ํŒ๋‹จํ•ด ์†Œ์ˆ˜๋ผ๋ฉด ๊ฐ’์„ String์œผ๋กœ ๋ฐ”๊พผ ํ›„ contains ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ D๋ฅผ ํฌํ•จํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค. ํฌํ•จํ•˜๋ฉด result๋ฅผ 1 ์ฆ๊ฐ€์‹œํ‚จ๋‹ค. ์ตœ์ข… ์ฃผ์–ด์ง„ ๋ฒ”์œ„ ๋‚ด์—์„œ ์ˆซ์ž D๋ฅผ ํฌํ•จํ•˜๋Š” ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜ result๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.