๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
โœจ Algorithm

[๋ฐฑ์ค€/C++] 4948๋ฒˆ : ๋ฒ ๋ฅดํŠธ๋ž‘ ๊ณต์ค€

by nitronium102 2021. 8. 8.

๋ฌธ์ œ

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

ํ’€์ด

- ์ž…๋ ฅ์ด 0์ผ ๋•Œ ์ž…๋ ฅ ์ข…๋ฃŒ

- N ์ดˆ๊ณผ 2N ์ดํ•˜

์œ„์˜ ๋‘ ์กฐ๊ฑด์„ ์ƒ๊ฐํ•˜๋ฉด ์ง€๋‚œ ๋ฌธ์ œ์™€ ๋น„์Šทํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ ํ’€ ์ˆ˜ ์žˆ๋‹ค. 

#include <iostream>
#include <cmath>
using namespace std;
int MAX = 123456*2;

int main() {
  int N=-1, cnt = 0, limit;
  bool isPrime[MAX+1];
  while (true){
    cin >> N;
    if (N == 0)
      break;
    fill_n(isPrime, MAX+1, true);
    isPrime[0] = false;
    isPrime[1] = false;

    for (int i=2; i<=sqrt(2*N); i++){
      if (isPrime[i]){
        for (int j=2*i; j<=2*N; j+=i){
          if (2*N > MAX + 1)
            break;
          isPrime[j] = false;
        } 
      }
    }

    for (int i = N+1; i<=2*N; i++){
      if (isPrime[i])
        cnt += 1;
    }

    cout << cnt << "\n";
    cnt = 0;
  }
}

https://www.acmicpc.net/problem/4948

 

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

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

www.acmicpc.net

 

๋Œ“๊ธ€