From 92e07981cfdce259a6d846724f4068ad260ab6e5 Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Wed, 10 Nov 2021 01:38:51 +0300 Subject: [PATCH] feat(rust): add prime number kata --- rust/tests/8_prime_number.rs | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 rust/tests/8_prime_number.rs diff --git a/rust/tests/8_prime_number.rs b/rust/tests/8_prime_number.rs new file mode 100644 index 0000000..a5eed57 --- /dev/null +++ b/rust/tests/8_prime_number.rs @@ -0,0 +1,42 @@ +fn is_prime(x: i64) -> bool { + match x { + 2 | 3 | 5 | 7 => true, + x if x < 2 || x % 2 == 0 => false, + x => { + let last = (x as f64).sqrt() as i64; + !(3..=last).step_by(2).any(|n| x % n == 0) + } + } +} + +#[test] +fn basic_tests() { + assert!(!is_prime(0), "0 is not prime"); + assert!(!is_prime(1), "1 is not prime"); + assert!(is_prime(2), "2 is prime"); + assert!(is_prime(73), "73 is prime"); + assert!(!is_prime(75), "75 is not prime"); + assert!(!is_prime(-1), "-1 is not prime"); +} + +#[test] +fn prime_tests() { + assert!(is_prime(3), "3 is prime"); + assert!(is_prime(5), "5 is prime"); + assert!(is_prime(7), "7 is prime"); + assert!(is_prime(41), "41 is prime"); + assert!(is_prime(5099), "5099 is prime"); +} + +#[test] +fn not_prime_tests() { + assert!(!is_prime(4), "4 is not prime"); + assert!(!is_prime(6), "6 is not prime"); + assert!(!is_prime(8), "8 is not prime"); + assert!(!is_prime(9), "9 is not prime"); + assert!(!is_prime(45), "45 is not prime"); + assert!(!is_prime(-5), "-5 is not prime"); + assert!(!is_prime(-8), "-8 is not prime"); + assert!(!is_prime(-41), "-41 is not prime"); + assert!(!is_prime(183790093), "183790093 is not prime"); +}