Skip to content

Instantly share code, notes, and snippets.

@shadeglare
Last active April 1, 2023 15:34
Show Gist options
  • Save shadeglare/0ce7f2c7e698a2e55bcafdb94b7c86f3 to your computer and use it in GitHub Desktop.
Save shadeglare/0ce7f2c7e698a2e55bcafdb94b7c86f3 to your computer and use it in GitHub Desktop.
Different approaches to generate prime numbers
pub fn generate(count: usize) -> Vec<u32> {
assert!(count > 0);
let mut probe = 1;
let mut primes = {
let mut vec = Vec::with_capacity(count);
vec.push(2u32);
vec
};
while primes.len() < count {
let candidate = 2 * probe + 1;
if primes.iter().all(|n| candidate % n != 0) {
primes.push(candidate);
}
probe += 1;
}
primes
}
pub struct Sequence {
probe: u32,
cache: Vec<u32>,
}
impl Sequence {
fn new() -> Self {
Self {
probe: 1,
cache: vec![],
}
}
}
pub fn sequence() -> Sequence {
Sequence::new()
}
impl Iterator for Sequence {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
println!("next");
if self.cache.is_empty() {
self.cache.push(2);
} else {
loop {
let candidate = 2 * self.probe + 1;
self.probe += 1;
if self.cache.iter().all(|&n| candidate % n != 0) {
self.cache.push(candidate);
break;
}
}
}
self.cache.last().copied()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment