Last active
November 26, 2018 10:33
-
-
Save BartMassey/0fa845b7a1d9a910b26db10e401995c6 to your computer and use it in GitHub Desktop.
Various prime number implementations, including a buggy one
This file contains hidden or 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
| // https://www.reddit.com/r/rust/comments/a0g730/new_to_rust_discouraged_by_slowrunning_code/ | |
| fn nth_prime_bad(initial: u64) -> u64 { | |
| let mut prime_count = 0; | |
| let mut curr = 2; | |
| let mut prime = None; | |
| while prime_count < initial { | |
| let mut denom = 2; | |
| while denom < curr { | |
| if curr % denom == 0 { | |
| curr = curr + 1; | |
| continue; | |
| } | |
| denom += 1; | |
| } | |
| prime = Some(curr); | |
| curr = curr + 1; | |
| prime_count = prime_count + 1; | |
| } | |
| return prime.unwrap(); | |
| } | |
| fn nth_prime(initial: u64) -> u64 { | |
| let mut prime_count = 0; | |
| let mut curr = 2; | |
| let mut prime = None; | |
| 'next_candidate: while prime_count < initial { | |
| let mut denom = 2; | |
| while denom < curr { | |
| if curr % denom == 0 { | |
| curr = curr + 1; | |
| continue 'next_candidate; | |
| } | |
| denom += 1; | |
| } | |
| prime = Some(curr); | |
| curr = curr + 1; | |
| prime_count = prime_count + 1; | |
| } | |
| return prime.unwrap(); | |
| } | |
| fn nth_prime_clean(n: u64) -> u64 { | |
| fn is_prime(p: u64) -> bool { | |
| for d in 2..p { | |
| if p % d == 0 { | |
| return false; | |
| } | |
| } | |
| true | |
| } | |
| let mut count = 0; | |
| for candidate in 2.. { | |
| if is_prime(candidate) { | |
| count += 1; | |
| if count == n { | |
| return candidate; | |
| } | |
| } | |
| } | |
| panic!("ran out of candidates"); | |
| } | |
| fn nth_prime_functional(n: u64) -> u64 { | |
| let is_prime = |&c: &u64| (2..c).all(|d| c % d != 0); | |
| (2..).filter(is_prime).nth((n - 1) as usize) | |
| .expect("ran out of candidates") | |
| } | |
| const N: u64 = 100; | |
| fn main() { | |
| println!("{}", nth_prime_bad(N)); | |
| println!("{}", nth_prime(N)); | |
| println!("{}", nth_prime_clean(N)); | |
| println!("{}", nth_prime_functional(N)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment