Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Created July 2, 2015 23:05
Show Gist options
  • Save lovasoa/78bb1e5043d1a7d64243 to your computer and use it in GitHub Desktop.
Save lovasoa/78bb1e5043d1a7d64243 to your computer and use it in GitHub Desktop.
compute prime numbers in Rust
struct Primes {
primes : Vec<u64>,
}
impl Primes {
fn new() -> Primes {
Primes{primes: vec![2]}
}
fn test(&self, totest: u64) -> bool {
let mut n = totest;
for i in &self.primes {
while n%(*i) == 0 {
n /= *i;
}
if n==1 {return false;}
}
return true;
}
}
impl Iterator for Primes {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let mut n = *self.primes.last().unwrap() + 1;
while !self.test(n) { n += 1; }
self.primes.push(n);
return Some(n);
}
}
fn main() {
for i in Primes::new() {println!("{}", i);}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment