Средне Решено: 0 Процент решений: 0%

Nth Prime

Return the nth prime number, counting 2 as the first.

Чему вы научитесь

  • Generate primes in order
  • Choose a sieve size large enough for the answer
  • Compare trial division with a sieve

Условие

Показать перевод

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

Примеры

Пример 1
Ввод:
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.

Пример 2
Ввод:
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. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

Принятых решений пока нет. Решите задачу и займите первое место.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.