From d49da0fe54251fbee190dc2adcdbffe787aecae7 Mon Sep 17 00:00:00 2001 From: Federico Stra Date: Tue, 26 Sep 2023 16:05:51 +0200 Subject: [PATCH] isqrt: add more tests --- library/core/tests/num/int_macros.rs | 17 +++++++++++++++++ library/core/tests/num/uint_macros.rs | 15 +++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/library/core/tests/num/int_macros.rs b/library/core/tests/num/int_macros.rs index a9ce8433864..dd0ea5e9238 100644 --- a/library/core/tests/num/int_macros.rs +++ b/library/core/tests/num/int_macros.rs @@ -299,6 +299,23 @@ macro_rules! int_module { assert_eq!((2 as $T).isqrt(), 1 as $T); assert_eq!((99 as $T).isqrt(), 9 as $T); assert_eq!((100 as $T).isqrt(), 10 as $T); + + let n_max: $T = (1024 * 1024).min($T::MAX as u128) as $T; + for n in 0..=n_max { + let isqrt: $T = n.isqrt(); + + assert!(isqrt.pow(2) <= n); + let (square, overflow) = (isqrt + 1).overflowing_pow(2); + assert!(overflow || square > n); + } + + for n in ($T::MAX - 127)..=$T::MAX { + let isqrt: $T = n.isqrt(); + + assert!(isqrt.pow(2) <= n); + let (square, overflow) = (isqrt + 1).overflowing_pow(2); + assert!(overflow || square > n); + } } #[test] diff --git a/library/core/tests/num/uint_macros.rs b/library/core/tests/num/uint_macros.rs index 9a8421c7b95..1ae7d048757 100644 --- a/library/core/tests/num/uint_macros.rs +++ b/library/core/tests/num/uint_macros.rs @@ -214,6 +214,21 @@ macro_rules! uint_module { assert_eq!((99 as $T).isqrt(), 9 as $T); assert_eq!((100 as $T).isqrt(), 10 as $T); assert_eq!($T::MAX.isqrt(), (1 << ($T::BITS / 2)) - 1); + + let n_max: $T = (1024 * 1024).min($T::MAX as u128) as $T; + for n in 0..=n_max { + let isqrt: $T = n.isqrt(); + + assert!(isqrt.pow(2) <= n); + assert!(isqrt + 1 == (1 as $T) << ($T::BITS / 2) || (isqrt + 1).pow(2) > n); + } + + for n in ($T::MAX - 255)..=$T::MAX { + let isqrt: $T = n.isqrt(); + + assert!(isqrt.pow(2) <= n); + assert!(isqrt + 1 == (1 as $T) << ($T::BITS / 2) || (isqrt + 1).pow(2) > n); + } } #[test]