01-09 04:37
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[BAEKJOON] ๋ฐฑ์ค€ ๊ธฐ๋ณธ ์ˆ˜ํ•™ 2 4948 :: ๋ฒ ์ŠคํŠธ๋ž‘ ๊ณต์ค€ ๋ณธ๋ฌธ

Algorithm/Baekjoon

[BAEKJOON] ๋ฐฑ์ค€ ๊ธฐ๋ณธ ์ˆ˜ํ•™ 2 4948 :: ๋ฒ ์ŠคํŠธ๋ž‘ ๊ณต์ค€

miinsun 2022. 4. 11. 13:31

๐Ÿ’ฌ  ๋ฌธ์ œ ์„ค๋ช…

๋ฒ ๋ฅดํŠธ๋ž‘ ๊ณต์ค€์€ ์ž„์˜์˜ ์ž์—ฐ์ˆ˜ 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

 

โ€‹

๐Ÿ’ป  Main.java

  • ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋กœ ์ „๋ฒ”์œ„(1 ~ 123,456 * 2)์˜ ์†Œ์ˆ˜๋ฅผ ํŒ๋ณ„ํ•ด์ค€๋‹ค.
  • '0'์ด ์ž…๋ ฅ๋˜๋ฉด ๋ฐ˜๋ณต๋ฌธ์„ ์ข…๋ฃŒํ•ด์ค€๋‹ค.
/* ๋ฐฑ์ค€ ๊ธฐ๋ณธ ์ˆ˜ํ•™ 2 - 4948 :: ๋ฒ ๋ฅดํŠธ๋ž‘ ๊ณต์ค€ */
import java.io.*;

public class Main {
	public static boolean[] prime;
	
	// ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด : ์†Œ์ˆ˜ ๊ตฌํ•˜๊ธฐ
	public static void isDecimal() {
		// true = ์†Œ์ˆ˜ ์•„๋‹˜ , false = ์†Œ์ˆ˜
		prime[0] = prime[1] = true;
		
		// ์ œ๊ณฑ๊ทผ๊นŒ์ง€ ๋ฐ˜๋ณต
		for(int i = 2; i <= Math.sqrt(prime.length); i++) {
			if(prime[i]) continue;
			for(int j = i * i; j < prime.length; j += i) {
				prime[j] = true;
			}
		}
	}
	
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		prime = new boolean[(123456 * 2) + 1];
		
		// ์ „๋ฒ”์œ„์˜ ์†Œ์ˆ˜ ์œ ๋ฌด ๊ตฌํ•˜๊ธฐ
		isDecimal();
		
		StringBuilder sb = new StringBuilder();
		while(true) {
			int n = Integer.parseInt(br.readLine());
			// 0์ด ์ž…๋ ฅ๋˜๋ฉด ์ข…๋ฃŒ
			if(n == 0) break;
			
			int cnt = 0;
			for(int i = n + 1; i <= 2 * n; i++) {
				if(!prime[i]) cnt++;
			}
			
			sb.append(cnt).append('\n');
		}
		
		System.out.println(sb);
		br.close();
	}
}
Comments