์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ/BOJ_Java

[BOJ/Step9] 1929 : ์†Œ์ˆ˜ ๊ตฌํ•˜๊ธฐ (JAVA)

NaNaRin๐Ÿ™ƒ 2021. 1. 19. 17:59

www.acmicpc.net/problem/1929

 

1929๋ฒˆ: ์†Œ์ˆ˜ ๊ตฌํ•˜๊ธฐ

์ฒซ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ M๊ณผ N์ด ๋นˆ ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. (1 ≤ M ≤ N ≤ 1,000,000) M์ด์ƒ N์ดํ•˜์˜ ์†Œ์ˆ˜๊ฐ€ ํ•˜๋‚˜ ์ด์ƒ ์žˆ๋Š” ์ž…๋ ฅ๋งŒ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net


๋ฌธ์ œ

M์ด์ƒ N์ดํ•˜์˜ ์†Œ์ˆ˜๋ฅผ ๋ชจ๋‘ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ M๊ณผ N์ด ๋นˆ ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. (1 ≤ M ≤ N ≤ 1,000,000) M์ด์ƒ N์ดํ•˜์˜ ์†Œ์ˆ˜๊ฐ€ ํ•˜๋‚˜ ์ด์ƒ ์žˆ๋Š” ์ž…๋ ฅ๋งŒ ์ฃผ์–ด์ง„๋‹ค.

 

์ถœ๋ ฅ

ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ, ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ์„œ๋Œ€๋กœ ์†Œ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

์˜ˆ์ œ ์ž…๋ ฅ

3 16

 

์˜ˆ์ œ ์ถœ๋ ฅ

3

5

7

11

13


ํ’€์ด

1. ์ˆซ์ž m๊ณผ n์„ ์ž…๋ ฅ๋ฐ›์•„ n+1ํฌ๊ธฐ์˜ ๋ฐฐ์—ด์„ ์ƒ์„ฑ. ๋ฐฐ์—ด์˜ idx๊ฐ’์ด ์ˆซ์ž๋ผ๊ณ  ๊ฐ€์ •ํ•œ๋‹ค.

2. ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด์— ๋”ฐ๋ผ < 2๋ถ€ํ„ฐ ๋ฃจํŠธn +1์˜ ๋ฒ„๋ฆผ์ˆ˜์ธ sqrt >์˜ ๋ฐฐ์ˆ˜์— (๋ฐฐ์ˆ˜๋Š” ์†Œ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ฏ€๋กœ) i๊ฐ€ j๋ž‘ ๊ฐ™์ง€ ์•Š์„๋•Œ (์ฒซ๋ฒˆ์งธ ์ˆ˜๋Š” ๋‚จ๊ฒจ๋‘๊ธฐ ์œ„ํ•ด) -1์„ ๋Œ€์ž…

3. m๊ณผ n ์‚ฌ์ด์˜ ๋ฐฐ์—ด์—์„œ -1์ด ์•„๋‹Œ ๋ฐฐ์—ด์˜ idx ๊ฐ’์„ ์ถœ๋ ฅ

 

import java.io.*;
import java.util.StringTokenizer;

public class B1929 {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		StringTokenizer st = new StringTokenizer(br.readLine());
		int m = Integer.parseInt(st.nextToken());
		int n = Integer.parseInt(st.nextToken());	
		
		int sqrt = (int)(Math.sqrt(n) + 1);
		
		int[] prime = new int[n+1];
		
		for(int i = 2; i <= sqrt; i++) {
			for(int j = i; j <= n; j+=i) {
				if (prime[j] == 0 && j != i && j % i == 0) {
					prime[j] = -1;
				}
			}
		}
		
		for(int i = m; i < prime.length; i++) {
			if(i != 1 && prime[i] != -1) {
				bw.write(i + "\n");
			}
		}
		bw.flush();
	}
}