KatInterview

Locate the Prime at a Given Position in the Prime Sequence

Math & Bit ManipulationAuto-graded · 20 test cases
EasyAuto-gradedMath & Bit Manipulationprimessievenumber-theory

Last updated

Find the prime at a given 1-based position in ascending order, which tests sieving, bounding the search range, and complexity reasoning.

Write a function that returns the prime number sitting at a given position when all primes are listed in increasing order.

The list starts 2, 3, 5, 7, 11, 13, and so on. Positions are counted from 1, so position 1 holds 2, position 2 holds 3, and position 3 holds 5.

Task

Given a positive integer position, return the prime found at that position in the ascending list of primes.

Input

  • position: an integer, the 1-based index into the ascending list of primes.

Output

  • A single integer: the prime at that index.

Notes

  • The function should stay fast for moderately large positions, up to about 100,000. Checking every integer one at a time with trial division is likely too slow in Python at that size.
  • If position is less than 1, the function should raise a ValueError.

Constraints

  • 1 <= position <= 100000
  • The returned value fits comfortably in a standard integer (the 100,000th prime is 1,299,709).

Examples

Example 1

Input: prime_at_position(1)

Output: 2

Example 2

Input: prime_at_position(2)

Output: 3

Example 3

Input: prime_at_position(3)

Output: 5

Example 4

Input: prime_at_position(10)

Output: 29

Hints

Hint 1

A sieve needs a fixed upper range. Think about how to estimate an upper bound for the k-th prime before you start sieving.

Hint 2

For k at least 6, the k-th prime is smaller than k * (ln k + ln ln k). Handle very small positions with a fixed limit, such as 15, which already contains 6 primes.

Hint 3

Run the Sieve of Eratosthenes up to the bound, starting each prime's crossing-out at p*p, then walk upward counting survivors until the count equals the requested position. If the count falls short, double the bound and retry.