문제
The primes in order are 2, 3, 5, 7, 11, 13, … Given a position n, return the prime at that position. Testing numbers one by one works for small n; for the larger inputs a sieve over a range that is big enough is much faster.
Implement nth_prime(n).
Input
n: The position in the list of primes, starting at 1.
Output
Return the nth prime. nth_prime(1) is 2.
제약 조건
1 ≤ n ≤ 100,000
예시
입력:
n = 6
예상 출력:
expected = 13
입력:
long long n = 6;
예상 출력:
long long expected = 13;
입력:
long n = 6;
예상 출력:
long expected = 13;
설명
The primes start 2, 3, 5, 7, 11, 13, so the sixth one is 13.
입력:
n = 1
예상 출력:
expected = 2
입력:
long long n = 1;
예상 출력:
long long expected = 2;
입력:
long n = 1;
예상 출력:
long expected = 2;
설명
The first prime is 2.
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
Counting primes as you find them works, but testing every number by trial division gets slow for large n.
힌트 2
The 100,000th prime is below 1,300,000, so a sieve of that size is enough.
힌트 3
If your sieve turns out too small, double it and try again.
예상 복잡도
O(m log log m) time, O(m) extra space, where m is the sieve size
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.