forked from alexfertel/rust-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prime_numbers.rs
38 lines (33 loc) · 862 Bytes
/
prime_numbers.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
pub fn prime_numbers(max: usize) -> Vec<usize> {
let mut result: Vec<usize> = Vec::new();
if max >= 2 {
result.push(2)
}
for i in (3..max + 1).step_by(2) {
let stop: usize = (i as f64).sqrt() as usize + 1;
let mut status: bool = true;
for j in (3..stop).step_by(2) {
if i % j == 0 {
status = false
}
}
if status {
result.push(i)
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
assert_eq!(prime_numbers(0), vec![]);
assert_eq!(prime_numbers(11), vec![2, 3, 5, 7, 11]);
assert_eq!(prime_numbers(25), vec![2, 3, 5, 7, 11, 13, 17, 19, 23]);
assert_eq!(
prime_numbers(33),
vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
);
}
}