Created
April 26, 2020 08:42
-
-
Save enrichman/25353533e7c640a55c84a715b6408d21 to your computer and use it in GitHub Desktop.
Find the nth prime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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