[ 백준 ] 15965 / K번째 소수

金弘均·2021년 9월 16일
0

Baekjoon Online Judge

목록 보기
213/228
post-thumbnail

# Appreciation

/*
 * Problem :: 15965 / K번째 소수
 *
 * Kind :: Math
 *
 * Insight
 * - 에라토스테네스의 체를 사용해야 할 것 같은데...
 *   범위를 어떻게 정해야 하지?
 *   + 500,000 번째 소수가 몇인지 알아야 한다
 *     # 일단 시간복잡도는 생각하지 말고 500,000 번째 소수를 찾아보자
 *       소수인지 아닌지 확인하려는 숫자를 n 이라고 하면
 *       for (int i=2; i*i<=n; i++) {
 *           if (n % i == 0) return false <= 소수 아님
 *       } return true <= 소수임
 *       로 찾아보았다
 *       -> 500,000 번째 소수는 7368787 이구나!!!
 *          이정도면 그냥 (bool) isPrime[7368787+1] 로 선언가능하다
 *          이제 에라토스테네스의 체를 사용해주자
 *
 * Point
 * - 구글링 하니 500,000 번째 소수가 몇인지 바로 알려주네...?
 */

# Code

//
//  BOJ
//  ver.C++
//
//  Created by GGlifer
//
//  Open Source

#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

#define endl '\n'

// Set up : Global Variables
/* None */

// Set up : Functions Declaration
bool isPrime(long num);


int main()
{
    // Set up : I/O
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    /* 500,000 번째 소수가 몇인지 확인 */
    // Test
    // int cnt = 0;
    // long num = 1;
    // while (cnt < 500'000) {
    //     num++;
    //     if (isPrime(num)) cnt++;
    // } cout << num << endl; // num = 500,000 번째 소수 = 7368787

    // Set up : Input
    int K; cin >> K;

    // Process
    int N = 7368787;
    bool isPrime[N+1];
    memset(isPrime, true, sizeof(isPrime));
    isPrime[0] = isPrime[1] = false;
    vector<int> primes; /* 소수가 저장되는 Vector */
    /* 에라토스테네스의 체 */
    for (int i=2; i<=N; i++) {
        if (isPrime[i]) { /* i 가 소수라면 */
            primes.push_back(i); /* primes 에 추가 */
            for (int j=2*i; j<=N; j+=i) {
                isPrime[j] = false; /* i 를 제외한 i 의 배수는 소수가 아님 */
            }
        }
    }

    // Control : Output
    cout << primes[K-1] << endl;
}

// Helper Functions
bool isPrime(long num)
/* num 이 소수이면 true 를 반환, 그 외 false 를 반환 */
{
    if (num == 0 || num == 1) return false;
    for (int i=2; i*i<=num; i++) {
        if (num%i == 0) return false;
    } return true;
}
profile
이런 미친 게임을 봤나! - 옥냥이

0개의 댓글