๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 1456_๊ฑฐ์˜ ์†Œ์ˆ˜

๋ฟŒ์•ผ._. 2024. 3. 12. 11:46

Gold V

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

< ๊ฑฐ์˜ ์†Œ์ˆ˜ >

 

๋ฌธ์ œ ํ’€์ด 

 

๋จผ์ € ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜์—ฌ ์†Œ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค. ์ด๋•Œ ๋ฒ”์œ„๋Š” B๊ฐ’์˜ ์ œ๊ณฑ๊ทผ์„ ์‚ฌ์šฉํ•œ๋‹ค. 

์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•˜๋Š” ๋ฐฐ์—ด์„ ํƒ์ƒ‰ํ•˜๋ฉฐ N์ œ๊ณฑ์„ ๊ตฌํ•œ๋‹ค. A๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ  B๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ๊ฑฐ์˜ ์†Œ์ˆ˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค.

 

 

 my solution (Java)

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

public class _1456_ { // ๊ฑฐ์˜ ์†Œ์ˆ˜

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

		long A = Long.parseLong(st.nextToken());
		long B = Long.parseLong(st.nextToken());

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

		int result = 0;
		for (int i = 1; i <= (int) Math.sqrt(B); i++) {
			if (!arr[i]) {
				long num = Long.valueOf(i);
				while ((num*=Long.valueOf(i)) <= B) {
					if(num >=A) {
						result += 1;
					}
					if(num > B/Long.valueOf(i)) {
						break;
					}
				}
			}
		}
		System.out.println(result);
	}
}
๋ณ€์ˆ˜)
A, B : ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ ๋ฒ”์œ„
arr : ์†Œ์ˆ˜ ํŒ๋ณ„
result : ๊ฑฐ์˜ ์†Œ์ˆ˜ ๊ฐœ์ˆ˜

 

๋‘ ์ •์ˆ˜ A์™€ B๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ์ด๋•Œ, A์™€ B์˜ ๋ฒ”์œ„๊ฐ€ 1 ์ด์ƒ 10์˜ 14์Šน ์ดํ•˜์ด๋ฏ€๋กœ long ํƒ€์ž…์œผ๋กœ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค.

์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜์—ฌ 0๋ถ€ํ„ฐ B์˜ ์ œ๊ณฑ๊ทผ๊นŒ์ง€ ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•œ๋‹ค.

 

์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•˜๋Š” ๋ฐฐ์—ด์„ ์ „์ฒด ํƒ์ƒ‰ํ•˜์—ฌ ์†Œ์ˆ˜๋ผ๋ฉด ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

1) N์ œ๊ณฑ์„ ๊ตฌํ•ด B์ดํ•˜์ด๊ณ  A์ด์ƒ์ด๋ฉด result+1์„ ํ•œ๋‹ค.

2) ๋‹ค์Œ N+1 ์ œ๊ณฑ์„ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค. num*Long.valueof(i) > B๋กœ ํ™•์ธํ•˜๋ฉด ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ๊ฐ€ ๋ฐœ์ƒํ•ด ์ •ํ™•ํ•œ ๋น„๊ต๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ num > B/Long.valueOf(i)๋กœ ํŒ๋‹จํ•œ๋‹ค.

 

๊ฑฐ์˜ ์†Œ์ˆ˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.


* ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ๋กœ ์ธํ•˜์—ฌ ์ œ๋Œ€๋กœ ๋œ ๋น„๊ต๋ฅผ ํ•˜์ง€ ๋ชปํ•ด ์ •ํ™•ํ•œ ๋‹ต์„ ๊ตฌํ•  ์ˆ˜ ์—†์—ˆ๋‹ค.