Last active
May 19, 2022 16:41
-
-
Save jsanders/8628582 to your computer and use it in GitHub Desktop.
Rust Sieve of Eratosthenes
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
// Find all prime numbers less than n | |
fn small_primes(bound: uint) -> ~[uint] { | |
// num is considered prime as long as primes[num] is true | |
// Start with all evens besides 2 filtered out | |
let mut primes = std::vec::from_fn(bound+1, |num| num == 2 || num & 1 != 0); | |
// Start at 3 and step by 2 because we've already filtered multiples of 2 | |
for num in count(3u, 2).filter(|&num| primes[num]).take_while(|&num| num * num <= bound) { | |
// Mark prime num's multiples non-prime | |
// We can start at num^2 because smaller non-primes have already been eliminated | |
for j in range_step_inclusive(num*num, bound, num) { primes[j] = false; } | |
} | |
primes. | |
move_iter(). | |
enumerate(). | |
skip(2). | |
filter_map(|(i, p)| if p {Some(i)} else {None}). | |
collect::<~[uint]>() | |
} | |
#[test] | |
fn test_small_primes() { | |
assert_eq!(small_primes(20), ~[2, 3, 5, 7, 11, 13, 17, 19]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A version that works with Rust v1+: https://gist.github.com/glebm/440bbe2fc95e7abee40eb260ec82f85c