-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcount-primes.rs
79 lines (65 loc) · 1.68 KB
/
count-primes.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
#![allow(dead_code, unused, unused_variables)]
fn main() {
assert_eq!(4, Solution::count_primes(10));
}
struct Solution;
impl Solution {
pub fn count_primes1(n: i32) -> i32 {
if n == 0 || n == 1 {
return 0;
}
// 0代表是质数,1代表非质数
let mut v = vec![0; (n - 2) as usize];
for i in 2..n {
if v[i as usize - 2] == 1 {
continue;
}
if Self::is_prim(i) {
v[i as usize - 2] = 0;
let mut m = i * 2;
while m < n {
v[m as usize - 2] = 1;
m *= 2;
}
} else {
v[i as usize - 2] = 1;
}
}
println!("{:?}", v);
v.into_iter().filter(|x| *x == 0).count() as i32
}
fn is_prim(n: i32) -> bool {
if n == 2 || n == 3 {
return true;
}
let mut i = 3;
while i * i <= n {
if n % i == 0 {
return false;
}
i += 2;
}
true
}
pub fn count_primes(n: i32) -> i32 {
if n == 0 || n == 1 {
return 0;
}
// 0代表是质数,1代表非质数
let mut v = vec![true; n as usize];
let mut start = 2usize;
let mut count = 0;
while start < n as usize {
if v[start] {
count += 1;
let mut start1 = start * 2;
while start1 < n as usize {
v[start1] = false;
start1 += start;
}
}
start += 1;
}
count
}
}