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

[BOJ/Step9] 4948 : ๋ฒ ๋ฅดํŠธ๋ž‘ ๊ณต์ค€ (JAVA)

NaNaRin๐Ÿ™ƒ 2021. 1. 19. 18:21

www.acmicpc.net/problem/4948

 

4948๋ฒˆ: ๋ฒ ๋ฅดํŠธ๋ž‘ ๊ณต์ค€

๋ฒ ๋ฅดํŠธ๋ž‘ ๊ณต์ค€์€ ์ž„์˜์˜ ์ž์—ฐ์ˆ˜ n์— ๋Œ€ํ•˜์—ฌ, n๋ณด๋‹ค ํฌ๊ณ , 2n๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์†Œ์ˆ˜๋Š” ์ ์–ด๋„ ํ•˜๋‚˜ ์กด์žฌํ•œ๋‹ค๋Š” ๋‚ด์šฉ์„ ๋‹ด๊ณ  ์žˆ๋‹ค. ์ด ๋ช…์ œ๋Š” ์กฐ์ œํ”„ ๋ฒ ๋ฅดํŠธ๋ž‘์ด 1845๋…„์— ์ถ”์ธกํ–ˆ๊ณ , ํŒŒํ”„๋ˆ„ํ‹ฐ ์ฒด๋น„์‡ผ

www.acmicpc.net


๋ฌธ์ œ

๋ฒ ๋ฅดํŠธ๋ž‘ ๊ณต์ค€์€ ์ž„์˜์˜ ์ž์—ฐ์ˆ˜ n์— ๋Œ€ํ•˜์—ฌ, n๋ณด๋‹ค ํฌ๊ณ , 2n๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์†Œ์ˆ˜๋Š” ์ ์–ด๋„ ํ•˜๋‚˜ ์กด์žฌํ•œ๋‹ค๋Š” ๋‚ด์šฉ์„ ๋‹ด๊ณ  ์žˆ๋‹ค.

์ด ๋ช…์ œ๋Š” ์กฐ์ œํ”„ ๋ฒ ๋ฅดํŠธ๋ž‘์ด 1845๋…„์— ์ถ”์ธกํ–ˆ๊ณ , ํŒŒํ”„๋ˆ„ํ‹ฐ ์ฒด๋น„์‡ผํ”„๊ฐ€ 1850๋…„์— ์ฆ๋ช…ํ–ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด, 10๋ณด๋‹ค ํฌ๊ณ , 20๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์†Œ์ˆ˜๋Š” 4๊ฐœ๊ฐ€ ์žˆ๋‹ค. (11, 13, 17, 19) ๋˜, 14๋ณด๋‹ค ํฌ๊ณ , 28๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์†Œ์ˆ˜๋Š” 3๊ฐœ๊ฐ€ ์žˆ๋‹ค. (17,19, 23)

์ž์—ฐ์ˆ˜ n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, n๋ณด๋‹ค ํฌ๊ณ , 2n๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

์ž…๋ ฅ์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๊ฐ ์ผ€์ด์Šค๋Š” n์„ ํฌํ•จํ•˜๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.

์ž…๋ ฅ์˜ ๋งˆ์ง€๋ง‰์—๋Š” 0์ด ์ฃผ์–ด์ง„๋‹ค.

 

์ถœ๋ ฅ

๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์— ๋Œ€ํ•ด์„œ, n๋ณด๋‹ค ํฌ๊ณ , 2n๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

์ œํ•œ

1 ≤ n ≤ 123,456

 

์˜ˆ์ œ ์ž…๋ ฅ 1

1

10

13

100

1000

10000

100000

0

 

์˜ˆ์ œ ์ถœ๋ ฅ 1

1

4

3

21

135

1033

8392


ํ’€์ด

1. ์ˆซ์ž n ์„ ์ž…๋ ฅ๋ฐ›์•„ m์— 2n์„ ๋Œ€์ž…ํ•˜๊ณ  , m+1 ํฌ๊ธฐ์˜ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•œ๋‹ค. n์ด 0์ผ๋•Œ ๋ฌดํ•œ๋ฃจํ”„๋ฅผ ํƒˆ์ถœํ•œ๋‹ค.

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

3. m๊ณผ n ์‚ฌ์ด์˜ ๋ฐฐ์—ด์—์„œ -1์ด ์•„๋‹๋•Œ๋งŒ count++, ์ตœ์ข… count๋ฅผ ๋ฒ„ํผ๋กœ ์ถœ๋ ฅ

4. ๋ฌดํ•œ๋ฃจํ”„๋ฅผ ํƒˆ์ถœํ•˜๋ฉด ๋ฒ„ํผ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

import java.io.*;
import java.util.Scanner;

public class B4948 {

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int n = 1;
		
		while(true) {
			n = sc.nextInt();
			if(n == 0) {
				break;
			}
			int m = 2 * n;
			int count = 0;
			
			int sqrt = (int)(Math.sqrt(m) + 1);
			
			int[] prime = new int[m+1];
			
			for(int i = 2; i <= sqrt; i++) {
				for(int j = i; j <= m; j+=i) {
					if (prime[j] == 0 && j != i) {
						prime[j] = -1;
					}
				}
			}
			
			for(int i = n+1; i < prime.length; i++) {
				if(i != 1 && prime[i] != -1) {
					count++;
				}
			}
			bw.write(count + "\n");		
			
		}
		
		bw.flush();
	}
}