Use a vector to store known primes.

This commit is contained in:
Nicolás Ortega Froysa 2021-03-01 16:12:23 +01:00
parent 5538ac7515
commit 9defe837e8

View File

@ -1,34 +1,39 @@
use std::env;
use std::collections::VecDeque;
fn main() {
let args:Vec<String> = 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<u64> = 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;
}