From 9defe837e819e46ffef942669f31e75c82da3350 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Ortega=20Froysa?= Date: Mon, 1 Mar 2021 16:12:23 +0100 Subject: [PATCH] Use a vector to store known primes. --- src/main.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 3375191..daaf740 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,34 +1,39 @@ use std::env; +use std::collections::VecDeque; fn main() { let args:Vec = env::args().collect(); // get the first `n` primes - let n:u64 = args[1].parse().unwrap(); + let n:usize = args[1].parse().unwrap(); + let mut primes:VecDeque = VecDeque::with_capacity(n); // first prime println!("{}", 2); - // already have first prime - let mut prime_count:u64 = 1; + primes.push_back(2); + let mut candidate:u64 = 3; - while prime_count < n + while primes.len() < n { - let mut aux:u64 = 3; + let mut i = 0; + let mut test_prime = primes.get(i).unwrap(); let mut is_prime = true; - while aux < (candidate as f64).sqrt() as u64 + while *test_prime < (candidate as f64).sqrt() as u64 { - if candidate % aux == 0 + if candidate % test_prime == 0 { is_prime = false; break; } - aux += 2; + + i += 1; + test_prime = primes.get(i).unwrap(); } if is_prime { println!("{}", candidate); - prime_count += 1; + primes.push_back(candidate); } candidate += 2; }