feat(rust): add prime number kata

This commit is contained in:
Dmitriy Pleshevskiy 2021-11-10 01:38:51 +03:00
parent c6b65c42cf
commit 92e07981cf

View file

@ -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");
}