From 9b4c0e9c5a83709a82e11af7930ce7e740d6ae77 Mon Sep 17 00:00:00 2001 From: Callum Fortune Date: Sat, 27 Apr 2024 00:52:09 +0100 Subject: [PATCH] Fix negative number hanging error --- src/miller_rabin.rs | 5 +++++ tests/miller_rabin_test.rs | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/miller_rabin.rs b/src/miller_rabin.rs index 9d7e534..be33836 100644 --- a/src/miller_rabin.rs +++ b/src/miller_rabin.rs @@ -4,6 +4,11 @@ use num_integer::Integer; use rand::thread_rng; pub fn miller_rabin(candidate: &BigInt) -> bool { + + if candidate < &BigInt::from(0) { + return false; + } + if candidate.is_even() { return *candidate == BigInt::from(2); // 2 is prime } diff --git a/tests/miller_rabin_test.rs b/tests/miller_rabin_test.rs index 0b000e6..3aea250 100644 --- a/tests/miller_rabin_test.rs +++ b/tests/miller_rabin_test.rs @@ -5,6 +5,20 @@ mod tests { use super::*; use num_bigint::BigInt; + #[test] + fn test_negative_numbers() { + + let primes = vec![ + BigInt::from(-150), + BigInt::from(-3), + BigInt::from(0), + BigInt::from(-1005050) + ]; + for prime in primes { + assert_eq!(miller_rabin(&prime), false); + } + } + #[test] fn test_primes() {