Last active
August 29, 2015 14:10
-
-
Save archer884/f2c1ed1d8cbd87a08e25 to your computer and use it in GitHub Desktop.
Fetch primes using sieve, average values less than one million
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
fn main() { | |
let (cnt, sum) = sieve(1000000).iter() | |
.fold((0u, 0u), |a, b| { | |
let (cnt, sum) = a; | |
(cnt + 1, sum + *b) | |
}); | |
println!("{}", sum as f32 / cnt as f32); | |
} | |
fn sieve(max: uint) -> Vec<uint> { | |
let mut values = Vec::from_fn(max, |_| true); | |
for n in range(2, max) { | |
if !values[n] { | |
continue; | |
} else { | |
for i in range(2, max) | |
.map(|un| un * n) | |
.take_while(|un| *un < max) { | |
values[i] = false; | |
} | |
} | |
} | |
values.iter().enumerate() | |
.skip(2) | |
.filter(|e| { let (_, prime) = *e; *prime }) | |
.map(|e| { let (value, _) = e; value }) | |
.collect() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment