Skip to content

Instantly share code, notes, and snippets.

@enrichman
Created April 26, 2020 08:42
Show Gist options
  • Save enrichman/25353533e7c640a55c84a715b6408d21 to your computer and use it in GitHub Desktop.
Save enrichman/25353533e7c640a55c84a715b6408d21 to your computer and use it in GitHub Desktop.
Find the nth prime
const MAX_SIZE: usize = 110_000;
pub fn nth(n: u32) -> u32 {
let primes = get_primes();
match primes.get(n as usize) {
None => {
println!("{}nth prime not found", n);
1
},
Some(prime) => *prime,
}
}
fn get_primes() -> Vec<u32> {
let mut candidates = [true; MAX_SIZE];
for i in 2..candidates.len() {
let mut j = i;
while j < candidates.len() {
j += i;
if j >= candidates.len() {
break;
}
candidates[j] = false;
}
}
let mut primes: Vec<u32> = Vec::new();
for i in 2..candidates.len() {
if candidates[i] {
primes.push(i as u32)
}
}
return primes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment