Skip to content

Instantly share code, notes, and snippets.

@lf94
Created October 23, 2017 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lf94/43cfa4a10ea595a8a79fa48d1755ea48 to your computer and use it in GitHub Desktop.
Save lf94/43cfa4a10ea595a8a79fa48d1755ea48 to your computer and use it in GitHub Desktop.
pub fn nth(n: usize) -> Result<u64, &'static str> {
if n <= 0 { Err("No primes below 1") }
else {
match (2..).filter(|&x| is_prime(x)).nth(n - 1) {
Some(n) => Ok(n),
None => Err("Iteration error")
}
}
}
fn is_prime(n: u64) -> bool {
let mut lhs = n / 2;
let mut rhs = 1;
let mut factors = 0;
while lhs > 0 {
let result = lhs * rhs;
if result == n {
factors += 1;
lhs -= 1;
rhs = 1;
} else if result > n {
lhs -= 1;
rhs = 1;
} else if result < n {
rhs += 1;
}
}
factors == 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment