Use a vector to store known primes.
This commit is contained in:
parent
5538ac7515
commit
9defe837e8
23
src/main.rs
23
src/main.rs
@ -1,34 +1,39 @@
|
|||||||
use std::env;
|
use std::env;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let args:Vec<String> = env::args().collect();
|
let args:Vec<String> = env::args().collect();
|
||||||
|
|
||||||
// get the first `n` primes
|
// 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
|
// first prime
|
||||||
println!("{}", 2);
|
println!("{}", 2);
|
||||||
// already have first prime
|
primes.push_back(2);
|
||||||
let mut prime_count:u64 = 1;
|
|
||||||
let mut candidate:u64 = 3;
|
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;
|
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;
|
is_prime = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
aux += 2;
|
|
||||||
|
i += 1;
|
||||||
|
test_prime = primes.get(i).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
if is_prime
|
if is_prime
|
||||||
{
|
{
|
||||||
println!("{}", candidate);
|
println!("{}", candidate);
|
||||||
prime_count += 1;
|
primes.push_back(candidate);
|
||||||
}
|
}
|
||||||
candidate += 2;
|
candidate += 2;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user