Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Last active September 19, 2021 08:59
Show Gist options
  • Select an option

  • Save MikuroXina/b794da0aa44388e8e6c616ecafacf74d to your computer and use it in GitHub Desktop.

Select an option

Save MikuroXina/b794da0aa44388e8e6c616ecafacf74d to your computer and use it in GitHub Desktop.
The implementation of Sieve of Eratosthenes.
use std::collections::HashMap;
fn sieve(max: usize) -> (Vec<usize>, HashMap<usize, usize>) {
let mut found_primes = vec![];
let mut found_least_factor = HashMap::with_capacity(max + 1);
for n in 2..=max {
let factor = *found_least_factor.entry(n).or_insert_with(|| {
found_primes.push(n);
n
});
found_primes
.iter()
.map(|&prime| (prime, prime * n))
.take_while(|&(prime, nth_prime)| prime <= factor && nth_prime <= max)
.for_each(|(prime, nth_prime)| {
found_least_factor.insert(nth_prime, prime);
});
}
(found_primes, found_least_factor)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment