diff --git a/Cargo.lock b/Cargo.lock index e9174a6..326d429 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,6 +12,10 @@ version = "0.1.0" name = "convert_sorted_list_to_binary_search_tree" version = "0.1.0" +[[package]] +name = "count_primes" +version = "0.1.0" + [[package]] name = "course_schedule_iii" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 298d8ba..ce301d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,4 +20,5 @@ members = [ "convert_sorted_list_to_binary_search_tree", "delete_operation_for_two_strings", "construct_target_array_with_multiple_sums", + "count_primes", ] diff --git a/count_primes/Cargo.toml b/count_primes/Cargo.toml new file mode 100644 index 0000000..220c254 --- /dev/null +++ b/count_primes/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "count_primes" +version = "0.1.0" +authors = ["Ryan Li "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/count_primes/src/lib.rs b/count_primes/src/lib.rs new file mode 100644 index 0000000..10af1b9 --- /dev/null +++ b/count_primes/src/lib.rs @@ -0,0 +1,62 @@ +/*! + * https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/599/week-2-may-8th-may-14th/3738/ + */ + +pub struct Solution {} + +impl Solution { + // /// a normal way + // pub fn count_primes(n: i32) -> i32 { + // (0..n) + // .filter(|x| *x == 2 || *x % 2 != 0) + // .filter(|x| Self::is_prime(x)) + // .count() as i32 + // } + + // fn is_prime(x: &i32) -> bool { + // *x > 1 && !(2..*x).filter(|i| i * i <= *x).any(|i| *x % i == 0) + // } + + pub fn count_primes(n: i32) -> i32 { + if n <= 2 { + return 0; + } + + let n = n as usize; + let mut nums = vec![true; n]; + nums[0] = false; + nums[1] = false; + let mut i = 2; + while i * i < n { + if nums[i] { + let mut j = 2; + while i * j < n { + nums[i * j] = false; + j += 1; + } + } + i += 1; + } + nums.iter().filter(|&&x| x).count() as i32 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert_eq!(Solution::count_primes(10), 4); + } + + #[test] + fn example_2() { + assert_eq!(Solution::count_primes(0), 0); + } + + #[test] + fn example_3() { + assert_eq!(Solution::count_primes(1), 0); + } +}