Skip to content

Instantly share code, notes, and snippets.

@jsanders
Last active May 19, 2022 16:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsanders/8628582 to your computer and use it in GitHub Desktop.
Save jsanders/8628582 to your computer and use it in GitHub Desktop.
Rust Sieve of Eratosthenes
// 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]);
}
@glebm
Copy link

glebm commented Feb 23, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment