Created
July 2, 2015 23:05
-
-
Save lovasoa/78bb1e5043d1a7d64243 to your computer and use it in GitHub Desktop.
compute prime numbers in 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
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