From 606067151f5cb65126351475dfc0117d9e25d156 Mon Sep 17 00:00:00 2001 From: Trivernis Date: Thu, 13 Feb 2020 09:50:02 +0100 Subject: [PATCH] Optimize calculations and Remove File IO --- src/main.rs | 37 ++++++++++++++----------------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/src/main.rs b/src/main.rs index 3c2f9eb..559fdac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,10 +2,7 @@ use may::go; use may::sync::mpmc::{channel, Sender}; use num_cpus; use std::env; -use std::fs::OpenOptions; -use std::io::prelude::*; -use std::io::BufWriter; -use std::time::Instant; +use std::time::{Instant, Duration}; fn main() { may::config().set_workers(num_cpus::get()); @@ -19,13 +16,6 @@ fn main() { if &start % 2 == 0 { start += 1; } - let file = OpenOptions::new() - .write(true) - .append(true) - .create(true) - .open("primes.txt") - .unwrap(); - let mut buffer = BufWriter::new(file); println!("Starting {} threads", num_threads); for i in 0u16..num_threads { let tx = tx.clone(); @@ -35,25 +25,17 @@ fn main() { println!("Started thread {}", i); } let time_start = Instant::now(); - let mut prime_count = 0; let mut primes: Vec = vec![]; + primes.push(2); // receives all prime numbers via the channel receiver. // The received prime numbers are stored in a vector loop { - let result = rx.recv(); + let result = rx.recv_timeout(Duration::from_millis(10)); match result { Err(_) => break, Ok(prime) => { - prime_count += 1; primes.push(prime); println!("\r{: <30}", prime); - print!( - "{} Primes/s", - prime_count as f64 / time_start.elapsed().as_secs_f64() - ); - if let Err(e) = buffer.write(&format!("{}\n", prime).into_bytes()) { - panic!(e); - } } } } @@ -61,7 +43,9 @@ fn main() { for prime in primes { prime_sum += prime as u128; } + println!(); println!("Prime Sum: {}", prime_sum); + println!("Solution took: {} ms", time_start.elapsed().as_millis()) } /// Calculates primes and increases by incr with every iteration @@ -71,13 +55,20 @@ fn get_primes(start: u64, incr: u64, stop_after: u64, tx: &Sender) { let mut num = start; while num < stop_after { let mut is_prime = true; - if (num < 3) | (&num % 2 == 0) { + if num == 2 { + tx.send(num).unwrap(); + num += incr; + continue; + } + if (num < 2) | (num != 2 && num % 2 == 0) { num += incr; continue; } - for i in (3u64..&num / 2).step_by(2) { + let max = (num as f64).sqrt().ceil() as u64; + for i in (3u64..=max).step_by(2) { if num % i == 0 { is_prime = false; + break; } } if is_prime {