B:BD[
2.481] → [
2.481:547]
unimplemented!("What is the 0-indexed {}th prime number?", n)
// List size approximation is insufficient for values of n = 0, 1, 2, 3, 4, 5, 6, 9 and 11, with the greatest difference of 4 when n = 2, requiring this correction.
let corrected_n = if n > 11 { n as f64 } else { (n + 4) as f64 };
// Approximated size of the list required using the inverse of an approximation of the prime-counting function.
let list_size = (corrected_n * (corrected_n * corrected_n.ln()).ln()).ceil() as usize;
/*
Index at which we can stop marking new multiples.
Array representing list of numbers.
Prime count.
*/
let (limit, mut list, mut count) = (
(list_size as f64).sqrt() as usize + 1,
vec![true; list_size],
0,
);
for index in 2..list_size {
if list[index] {
count += 1;
if count > n {
// Might return incorrect value if values greater than u32::MAX are cast.
return index as u32;
}
if index < limit {
for multiple in (index * index..list_size).step_by(index) {
list[multiple] = false;
}
}
}
}
unreachable!();