N-th Prime Number
Problem
Print the n-th prime number. The first prime is 2, the second is 3, the third is 5, and so on.
Constraints
- 1 <= n <= 10000
Examples
Input
6
Output
13
Solutions
To find the n-th prime we need an upper limit. For n >= 6 the prime is below n * (ln n + ln ln n); for small n any small limit works. A sieve then marks all multiples of each prime.
/*
* Problem : Process a number.
* Input : One integer n.
* Output : The n-th prime.
* Approach: A sieve with a safe limit.
* Time : O(L log log L)
* Space : O(L)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(long n) {
// Step 1: A fixed limit of 120000 is enough for n up to 10000.
int limit = 120_000;
boolean[] composite = new boolean[limit + 1];
long count = 0;
// Step 2: Sieve of Eratosthenes. For each prime p, mark its multiples as composite.
for (int p = 2; p <= limit; p++) {
if (!composite[p]) {
count++;
if (count == n) {
return p;
}
for (long multiple = (long) p * p; multiple <= limit; multiple += p) {
composite[(int) multiple] = true;
}
}
}
return -1;
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(solve(n));
}
}
Hints (1)
- Why do we start marking at p * p?