Created
September 11, 2022 22:44
-
-
Save ddjerqq/29eaa229ccbb1a15e1129a3acd29f883 to your computer and use it in GitHub Desktop.
generate infinite prime numbers using the power of rust
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
| //! # sieve to generate prime numbers without an upper limit | |
| //! | |
| //! this is very fast, especially when built with --release | |
| //! | |
| //! # example: | |
| //! ``` | |
| //! for i in s { | |
| //! println!("{} ", i); | |
| //! } | |
| //! ``` | |
| use std::collections::HashSet; | |
| struct Sieve { | |
| primes: HashSet<usize>, | |
| current: usize, | |
| initial: Vec<usize>, | |
| } | |
| const INITIAL: [usize; 7] = [2, 3, 5, 7, 11, 13, 17]; | |
| impl Sieve { | |
| pub fn new() -> Self { | |
| Self { | |
| primes: HashSet::from(INITIAL), | |
| current: 19, | |
| initial: Vec::from(INITIAL), | |
| } | |
| } | |
| } | |
| impl Iterator for Sieve { | |
| type Item = usize; | |
| fn next(&mut self) -> Option<Self::Item> { | |
| // this method does not really work well with numbers below 17, | |
| // because their sqrts are low numbers and they cause problems | |
| if !self.initial.is_empty() { | |
| return Some(self.initial.remove(0)) | |
| } | |
| 'outer: loop { | |
| // we only need to iterate upto the sqrt of the number | |
| let sqrt = f64::sqrt(self.current as f64).round() as usize; | |
| for div in (3..=sqrt) | |
| .step_by(2) | |
| .filter(|div| self.primes.contains(div)) | |
| { | |
| if self.current % div == 0 { | |
| // if `number % divisor == 0`: | |
| // the number is not prime | |
| self.current += 2; | |
| continue 'outer; | |
| } | |
| } | |
| // if at the end of the for loop, if we could not find any divisors, the number is prime | |
| self.primes.insert(self.current); | |
| self.current += 2; | |
| return Some(self.current - 2) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment