Last active
August 29, 2015 14:12
-
-
Save archer884/3abf8b0b9ae3e38394ab to your computer and use it in GitHub Desktop.
Parallel prime finding nonsense
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
use std::iter::iterate; | |
use std::num::Float; | |
use std::sync::Future; | |
fn main() { | |
if let Some(n) = read_uint(1) { | |
let sum_of_primes = { | |
let block_size = if n > 999 { n / 20 } else { n }; | |
let mut futures = Vec::new(); | |
let mut vec = Vec::new(); | |
for i in iterate(1u, |mut i| { i += 1; i }).take(n) { | |
vec.push(i); | |
if vec.len() >= block_size { | |
futures.push(Future::spawn(move || { | |
vec.iter().filter(|i| is_prime(*i)) | |
.fold(0u, |mut a,b| { a += *b; a }) | |
})); | |
vec = Vec::new(); | |
} | |
} | |
if vec.len() > 0 { | |
futures.push(Future::spawn(move || { | |
vec.iter().filter(|i| is_prime(*i)) | |
.fold(0u, |mut a,b| { a += *b; a }) | |
})) | |
} | |
futures.iter_mut().fold(0u, |mut a, mut b| { a += b.get(); a }) | |
}; | |
println!("{}", sum_of_primes); | |
} else { | |
println!("usage: parallel_spike [NUMBER]"); | |
} | |
} | |
fn is_prime(n: &uint) -> bool { | |
match *n { | |
1 => false, | |
2 => true, | |
n => !range(2, (n as f32).sqrt().ceil() as uint + 1).any(|i| n % i == 0) | |
} | |
} | |
fn read_uint(n: uint) -> Option<uint> { | |
let args = std::os::args(); | |
if args.len() > n { | |
args[n].as_slice().parse::<uint>() | |
} else { | |
None | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment