Last active
September 19, 2021 08:59
-
-
Save MikuroXina/b794da0aa44388e8e6c616ecafacf74d to your computer and use it in GitHub Desktop.
The implementation of Sieve of Eratosthenes.
This file contains hidden or 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
| 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