Skip to content

Commit

Permalink
Improve Rust example program
Browse files Browse the repository at this point in the history
  • Loading branch information
fwsGonzo committed Nov 20, 2023
1 parent 3c21396 commit 8e8ff94
Showing 1 changed file with 44 additions and 3 deletions.
47 changes: 44 additions & 3 deletions binaries/rust/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,48 @@
// https://play.rust-lang.org/?gist=4d6abc78a8c0d205da57a17c02201d7c&version=stable&mode=release&edition=2015

/// Returns the nth prime.
///
/// It uses a sieve internally, with a size of roughly
/// `n * (n.ln() + n.ln().ln()` bytes. As a result, its
/// runtime is also bound loglinear by the upper term.
///
pub fn nth_prime(n: u32) -> Option<u64> {
if n < 1 {
return None;
}

// The prime counting function is pi(x) which is approximately x/ln(x)
// A good upper bound for the nth prime is ceil(x * ln(x * ln(x)))
let x = if n <= 10 { 10.0 } else { n as f64 };
let limit: usize = (x * (x * (x).ln()).ln()).ceil() as usize;
let mut sieve = vec![true; limit];
let mut count = 0;

// Exceptional case for 0 and 1
sieve[0] = false;
sieve[1] = false;

for prime in 2..limit {
if !sieve[prime] {
continue;
}
count += 1;
if count == n {
return Some(prime as u64);
}

for multiple in ((prime * prime)..limit).step_by(prime) {
sieve[multiple] = false;
}
}
None
}

fn main() {
// Statements here are executed when the compiled binary is called
assert_eq!(nth_prime(0), None);
assert_eq!(nth_prime(1), Some(2));
assert_eq!(nth_prime(2), Some(3));
assert_eq!(nth_prime(3), Some(5));

// Print text to the console
println!("Hello World!");
println!("Sieve(256000) == {}\n", nth_prime(256000).unwrap());
}

0 comments on commit 8e8ff94

Please sign in to comment.