Last active
August 29, 2015 14:03
-
-
Save robmiller/ab7bb2dca669d662f547 to your computer and use it in GitHub Desktop.
Project Euler #3 in Rust
This file contains 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 PrimeStream { | |
current: int | |
} | |
impl PrimeStream { | |
fn new() -> PrimeStream { | |
PrimeStream { current: 1 } | |
} | |
} | |
impl Iterator<int> for PrimeStream { | |
fn next(&mut self) -> Option<int> { | |
self.current += 1; | |
fn _is_prime(n: int) -> bool { | |
let f = n as f32; | |
let max = match f.sqrt().to_int() { | |
Some(x) => x, | |
None => return false | |
}; | |
if n % 2 == 0 { | |
return false; | |
} | |
let mut multiple = 3; | |
loop { | |
if multiple >= max { break; } | |
if n % multiple == 0 { | |
return false; | |
} | |
multiple += 2; | |
} | |
return true; | |
} | |
while !_is_prime(self.current) { | |
self.current += 1; | |
} | |
Some(self.current) | |
} | |
} | |
fn main() { | |
let mut largest = 0; | |
let target = 600851475143; | |
for n in PrimeStream::new().take_while(|n: &int| *n <= target) { | |
if n % 10000 == 0 { | |
println!("{}", n); | |
} | |
if target % n == 0 { | |
largest = n; | |
println!("New largest: {}", largest); | |
} | |
} | |
println!("Final largest: {}", largest); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment