-
Notifications
You must be signed in to change notification settings - Fork 1
/
rusty_sieve.rs
90 lines (70 loc) · 1.7 KB
/
rusty_sieve.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Dominic Gasperini
// Rust Prime Sieve
// namespace
use std::env;
use std::process;
use std::convert::TryInto;
// main!
fn main() {
// gather command line arguments
let args: Vec<String> = env::args().collect();
// set command line arguments
let number: usize = args[1].parse().unwrap();
let pass_count: usize = args[2].parse().unwrap();
// create vector for primes and set all to true
let mut primes = Vec::new();
primes.resize(number, true);
// now run the sieve
for _ in 1..pass_count {
// reset array
primes.resize(number, true);
// run sieve
prime_sieve(&mut primes);
}
// check for valid primes
if !prime_check(&primes) {
process::exit(-1);
}
}
fn prime_sieve(primes: &mut Vec<bool>) {
// run the sieve
primes[0] = false;
primes[1] = false;
let size = primes.len() as f64;
let upper_limit = f64::sqrt(size) as usize + 1;
for p in 3..(upper_limit) {
if primes[p] {
for i in ((p * p)..(primes.len() - 1)) {
primes[i] = false;
}
}
}
}
fn prime_check(primes: &Vec<bool>) -> bool {
// check all numbers in the vector
for i in 0..primes.len()-1 {
if primes[i] {
if !is_prime(i.try_into().unwrap()) {
return false;
}
}
}
return true;
}
fn is_prime(number: i32) -> bool {
if number == 2 {
return true;
}
if number < 2 || number % 2 == 0 {
return false;
}
let mut i = 3;
let step = 2;
while (i*i) <= number {
if number % i == 0 {
return false;
}
i += step;
}
return true;
}