mykatas/rust/tests/8_prime_number.rs

43 lines
1.2 KiB
Rust
Raw Normal View History

2021-11-10 01:38:51 +03:00
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");
}