Skip to content

Commit fd6f41d

Browse files
committed
solve #204
1 parent 9235765 commit fd6f41d

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,4 @@ mod n0200_number_of_islands;
171171
mod n0201_bitwise_and_of_numbers_range;
172172
mod n0202_happy_number;
173173
mod n0203_remove_linked_list_elements;
174+
mod n0204_count_primes;

src/n0204_count_primes.rs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* [204] Count Primes
3+
*
4+
* Count the number of prime numbers less than a non-negative number, n.
5+
*
6+
* Example:
7+
*
8+
*
9+
* Input: 10
10+
* Output: 4
11+
* Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
12+
*
13+
*
14+
*/
15+
pub struct Solution {}
16+
17+
// submission codes start here
18+
19+
impl Solution {
20+
pub fn count_primes(n: i32) -> i32 {
21+
if n <= 2 { return 0 }
22+
let mut is_prime = vec![true; n as usize];
23+
is_prime[0] = false;
24+
is_prime[1] = false;
25+
let mut i = 2;
26+
while i * i < n {
27+
if !is_prime[i as usize] {
28+
i += 1;
29+
continue
30+
}
31+
let mut j = i * i;
32+
while j < n {
33+
is_prime[j as usize] = false;
34+
j += i;
35+
}
36+
i += 1;
37+
}
38+
let mut count = 0;
39+
for &v in is_prime.iter() {
40+
if v { count += 1 }
41+
}
42+
count
43+
}
44+
45+
}
46+
47+
// submission codes end
48+
49+
#[cfg(test)]
50+
mod tests {
51+
use super::*;
52+
53+
#[test]
54+
fn test_204() {
55+
assert_eq!(Solution::count_primes(10), 4);
56+
assert_eq!(Solution::count_primes(2), 0);
57+
assert_eq!(Solution::count_primes(3), 1);
58+
assert_eq!(Solution::count_primes(5), 2);
59+
assert_eq!(Solution::count_primes(1), 0);
60+
assert_eq!(Solution::count_primes(120), 30);
61+
}
62+
}

0 commit comments

Comments
 (0)