Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. use std::collections::HashMap;
  2.  
  3. struct Sieve {
  4. composites: HashMap<u64, Vec<u64>>,
  5. current: u64,
  6. }
  7.  
  8. impl Default for Sieve {
  9. fn default() -> Self {
  10. Sieve {
  11. composites: HashMap::new(),
  12. current: 2,
  13. }
  14. }
  15. }
  16.  
  17. impl Sieve {
  18. pub fn new() -> Sieve {
  19. Default::default()
  20. }
  21. }
  22.  
  23. impl Iterator for Sieve {
  24. type Item = u64;
  25.  
  26. fn next(&mut self) -> Option<u64> {
  27. fn next_prime(composites: &mut HashMap<u64, Vec<u64>>, x: u64) -> u64 {
  28. match composites.get(&x) {
  29. Some(numbers) => {
  30. for num in numbers.to_owned() {
  31. composites
  32. .entry(x + num)
  33. .and_modify(|v| v.push(num))
  34. .or_insert_with(|| vec![num]);
  35. }
  36. composites.remove(&x);
  37. next_prime(composites, x + 1)
  38. }
  39. None => {
  40. composites.insert(x * x, vec![x]);
  41. x
  42. }
  43. }
  44. }
  45.  
  46. let prime = next_prime(&mut self.composites, self.current);
  47. self.current = prime + 1; // This number will be the next to be tested
  48.  
  49. Some(prime)
  50. }
  51. }
  52.  
  53. fn main() {
  54. let mut sieve = Sieve::new();
  55.  
  56. assert_eq!(sieve.next(), Some(2));
  57. assert_eq!(sieve.next(), Some(3));
  58. assert_eq!(sieve.next(), Some(5));
  59. assert_eq!(sieve.next(), Some(7));
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement