Intermedio 0 resueltos 0% de aceptación

Nth Prime

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

Lo que aprenderás

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

Problema

Ver traducción

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.

Restricciones

1 ≤ n ≤ 100,000

Ejemplos

Ejemplo 1
Entrada:
n = 6

Salida esperada:
expected = 13
Entrada:
long long n = 6;

Salida esperada:
long long expected = 13;
Entrada:
long n = 6;

Salida esperada:
long expected = 13;

Explicación

The primes start 2, 3, 5, 7, 11, 13, so the sixth one is 13.

Ejemplo 2
Entrada:
n = 1

Salida esperada:
expected = 2
Entrada:
long long n = 1;

Salida esperada:
long long expected = 2;
Entrada:
long n = 1;

Salida esperada:
long expected = 2;

Explicación

The first prime is 2.

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

Counting primes as you find them works, but testing every number by trial division gets slow for large n.

Pista 2

The 100,000th prime is below 1,300,000, so a sieve of that size is enough.

Pista 3

If your sieve turns out too small, double it and try again.

Complejidad esperada

O(m log log m) time, O(m) extra space, where m is the sieve size

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Clasificación

Clasificación completa

La mejor solución aprobada de cada programador. Las más rápidas, ligeras y mejor valoradas van primero.

Aún no hay soluciones aprobadas. Resuélvelo y quédate el primer puesto.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.