Created
October 23, 2017 17:59
-
-
Save lf94/43cfa4a10ea595a8a79fa48d1755ea48 to your computer and use it in GitHub Desktop.
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
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