Locate the Prime at a Given Position in the Prime Sequence
Math & Bit ManipulationAuto-graded · 20 test casesLast 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
positionis less than 1, the function should raise aValueError.
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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Testing integers one by one for primality works but is slow. Instead, do this in two steps:
- Bound the answer. Pick an upper limit
Lthat is guaranteed to be at least as large as the requested prime. For positionk >= 6, a classical result givesp_k < k * (ln k + ln ln k). Fork < 6the formula is unreliable, so use a fixed limit of 15, since the primes up to 15 are 2, 3, 5, 7, 11, 13 (six of them). - Sieve, then count. Run the Sieve of Eratosthenes on
[0, L], then scan upward counting primes and return the value at which the count reachesposition.
A small +10 margin guards against floating-point truncation. As a safety net, if the scan ends with too few primes, the limit is doubled and the sieve is rerun.
The sieve
- Start with a
bytearrayof ones and mark 0 and 1 as non-prime. - For each
pfrom 2 toisqrt(L), ifpis still marked, cross outp*p, p*p+p, .... - Starting at
p*pis safe because smaller multiples have a smaller prime factor that already crossed them out. - Stopping at
sqrt(L)is safe because every composite up toLhas a prime factor at mostsqrt(L). - Crossing out is done with a single slice assignment, which runs at C speed. The slice length
((L - start) // p) + 1matches the number of elements in the slice exactly.
Why it is correct
- A number
m >= 2stays marked exactly when no prime up tosqrt(m)divides it, which is the definition of primality. - The bound guarantees the requested prime lies inside the sieved range; the doubling loop keeps the function correct even if it did not.
- Scanning in increasing order means the value where the count equals
positionis theposition-th smallest prime.
Complexity
With L = Theta(k log k):
- Time:
O(L log log L)for the sieve plusO(L)for the scan, soO(k log k log log k)overall. - Space:
O(L)bytes, about 1.4 MB fork = 100000.
Edge cases
position = 1returns 2, using the fixed limit.position < 1raisesValueError.- For very large positions, a segmented sieve would reduce memory use.
Reference solution
import math
def prime_at_position(position: int) -> int:
if position < 1:
raise ValueError("position must be positive")
if position < 6:
limit = 15
else:
limit = int(position * (math.log(position) + math.log(math.log(position)))) + 10
while True:
sieve = bytearray(b"\x01") * (limit + 1)
sieve[0:2] = b"\x00\x00"
for p in range(2, math.isqrt(limit) + 1):
if sieve[p]:
start = p * p
sieve[start:limit + 1:p] = b"\x00" * (((limit - start) // p) + 1)
count = 0
for value in range(2, limit + 1):
if sieve[value]:
count += 1
if count == position:
return value
limit *= 2