-
Notifications
You must be signed in to change notification settings - Fork 46
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
44 additions
and
3 deletions.
There are no files selected for viewing
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
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()); | ||
} |