Skip to content

Instantly share code, notes, and snippets.

@archer884
Last active August 29, 2015 14:10
Show Gist options
  • Save archer884/f2c1ed1d8cbd87a08e25 to your computer and use it in GitHub Desktop.
Save archer884/f2c1ed1d8cbd87a08e25 to your computer and use it in GitHub Desktop.
Fetch primes using sieve, average values less than one million
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