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

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

NaNaRin๐Ÿ™ƒ 2021. 2. 15. 18:18

www.acmicpc.net/problem/4948

 

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

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

www.acmicpc.net


 

n๊นŒ์ง€์˜ ์ˆ˜๋ฅผ ๋ฏธ๋ฆฌ ์†Œ์ˆ˜ ํŒ๋ณ„ ํ›„ ํ™•์ธ
1. prime ๋ฆฌ์ŠคํŠธ์•ˆ์— False, False, True, … ๋ฅผ ์ €์žฅํ•œ๋‹ค

    -> prime์˜ ์ธ๋ฑ์Šค ์ˆซ์ž๊ฐ€ ์†Œ์ˆ˜๋ฉด True, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด False๋ฅผ ์ €์žฅํ•  ๊ฒƒ์ด๋‹ค

2. ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋ฅผ ์ด์šฉํ•œ๋‹ค.

  2-1. i๋Š” 2๋ถ€ํ„ฐ 2n์˜ ์ œ๊ณฑ๊ทผ๊นŒ์ง€์˜ ์ˆœ์„œ๋Œ€๋กœ ๋ฐฐ์ˆ˜๋ฅผ ์ง€์›Œ๋‚˜๊ฐˆ๊ฒƒ.

          -> i์˜ ๋ฐฐ์ˆ˜๋Š” i๋กœ ๋‚˜๋ˆ ์ง€๊ธฐ ๋•Œ๋ฌธ์— ์†Œ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ฏ€๋กœ prime[i]๋ฅผ False๋กœ ๋ณ€๊ฒฝ

  2-2. prime[i] ๊ฐ€ True์ผ ๋•Œ๋งŒ ๋ฐฐ์ˆ˜๋ฅผ ์ง€์šด๋‹ค -> False๋Š” ์ด๋ฏธ ๋” ์ด์ „์— ์ง€์›Œ์ง„ ๊ฒƒ์ด๋ฏ€๋กœ ๋ฐฐ์ˆ˜ ๋˜ํ•œ ์ด๋ฏธ False

  2-3. i*i๋ถ€ํ„ฐ i์”ฉ ๋”ํ•˜๋ฉด์„œ False๋กœ ๋ณ€๊ฒฝ. i์˜ 2๋ฐฐ, 3๋ฐฐ, …, n๋ฐฐ๋Š” ๋” ์ด์ „์— ์ด๋ฏธ ์ง€์›Œ์กŒ์„๊ฒƒ์ด๋ฏ€๋กœ i*i๋ถ€ํ„ฐ ์ง€์›Œ๋‚˜๊ฐ„๋‹ค

3. ์ž…๋ ฅ๋ฐ›์€ n๋ถ€ํ„ฐ 2n๊นŒ์ง€ prime[n+1] ~prime[2n]์˜ ๊ฐ’์„ ํ™•์ธํ•˜์—ฌ True์ผ ๋•Œ๋งŒ count++

4. count ์ถœ๋ ฅ

# 4948-1.py

while True:
    n = int(input())
    if n == 0:
        break

    count = 0
    prime = [False, False] + [True] * (2*n - 1)
    for i in range(2, int(pow(2*n, 0.5) + 1)):
        if prime[i]:
            for j in range(i * i, 2*n + 1, i):
                prime[j] = False

    for i in range(n+1, 2*n+1):
        if prime[i]:
            count += 1
    print(count)

 

๋ฐ”๋กœ ์ด์ „์˜ 1929 ๋ฌธ์ œ์—์„œ ํ‘ผ ๋ฐฉ์‹ ๊ทธ๋Œ€๋กœ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋Š”๋ฐ

์†๋„๊ฐ€ ๋Š๋ฆฌ๋˜ ๋ฐฉ๋ฒ•์€ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋˜๊ณ , ์†๋„๊ฐ€ ๋น ๋ฅด๋˜ ๋ฐฉ๋ฒ•๋„ ์‹œ๊ฐ„์ด ์—„์ฒญ ๋Š˜์–ด๋‚ฌ๋‹ค

ํ•˜์ง€๋งŒ ์˜คํžˆ๋ ค ๋ฉ”๋ชจ๋ฆฌ๋Š” ์ค„์–ด๋“ค์—ˆ๋‹ค๋Š”์ .. 1929๋ฒˆ ๋ฌธ์ œ๊ฐ€ ๋ฒ”์œ„๊ฐ€ ๋” ๋„“์–ด์„œ ๊ทธ๋Ÿฐ๊ฒƒ ๊ฐ™๋‹ค

4948๋ฌธ์ œ๋Š” prime ๋ฆฌ์ŠคํŠธ๋ฅผ ์žฌ์‚ฌ์šฉ ํ•ด์„œ ์ค„์–ด๋“  ๋“ฏ? ๋ฒ”์œ„๋Š” ๊ฑฐ์˜ 10๋ฐฐ ์ฐจ์ด๋‚˜๋‹ˆ๊นŒ

 

 

+ ์ตœ๋Œ€ ๋ฒ”์œ„๋งŒํผ ์†Œ์ˆ˜๋ฅผ ๋ฏธ๋ฆฌ ํŒ๋ณ„ํ•ด prime์— ์ €์žฅํ•˜๋ฉด ์†๋„๊ฐ€ ํ›จ์”ฌ ๋นจ๋ผ์ง„๋‹ค!

# 4948-2.py

N = 123456 * 2 + 1

prime = [False, False] + [True] * (N - 1)
for i in range(2, int(pow(N, 0.5) + 1)):
    if prime[i]:
        for j in range(i * i, N + 1, i):
            prime[j] = False

while True:
    n = int(input())
    if n == 0:
        break
    count = 0
    for i in range(n+1, 2*n+1):
        if prime[i]:
            count += 1
    print(count)