malachite_base/num/arithmetic/
divisible_by.rs

1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::arithmetic::traits::DivisibleBy;
10use crate::num::basic::signeds::PrimitiveSigned;
11use crate::num::basic::unsigneds::PrimitiveUnsigned;
12
13fn divisible_by_unsigned<T: PrimitiveUnsigned>(x: T, other: T) -> bool {
14    x == T::ZERO || other != T::ZERO && x % other == T::ZERO
15}
16
17macro_rules! impl_divisible_by_unsigned {
18    ($t:ident) => {
19        impl DivisibleBy<$t> for $t {
20            /// Returns whether a number is divisible by another number; in other words, whether the
21            /// first number is a multiple of the second.
22            ///
23            /// This means that zero is divisible by any number, including zero; but a nonzero
24            /// number is never divisible by zero.
25            ///
26            /// $f(x, m) = (m|x)$.
27            ///
28            /// $f(x, m) = (\exists k \in \N : x = km)$.
29            ///
30            /// # Worst-case complexity
31            /// Constant time and additional memory.
32            ///
33            /// # Examples
34            /// See [here](super::divisible_by#divisible_by).
35            #[inline]
36            fn divisible_by(self, other: $t) -> bool {
37                divisible_by_unsigned(self, other)
38            }
39        }
40    };
41}
42apply_to_unsigneds!(impl_divisible_by_unsigned);
43
44fn divisible_by_signed<T: PrimitiveSigned>(x: T, other: T) -> bool {
45    x == T::ZERO
46        || x == T::MIN && other == T::NEGATIVE_ONE
47        || other != T::ZERO && x % other == T::ZERO
48}
49
50macro_rules! impl_divisible_by_signed {
51    ($t:ident) => {
52        impl DivisibleBy<$t> for $t {
53            /// Returns whether a number is divisible by another number; in other words, whether the
54            /// first number is a multiple of the second.
55            ///
56            /// This means that zero is divisible by any number, including zero; but a nonzero
57            /// number is never divisible by zero.
58            ///
59            /// $f(x, m) = (m|x)$.
60            ///
61            /// $f(x, m) = (\exists k \in \Z : \ x = km)$.
62            ///
63            /// # Worst-case complexity
64            /// Constant time and additional memory.
65            ///
66            /// # Examples
67            /// See [here](super::divisible_by#divisible_by).
68            #[inline]
69            fn divisible_by(self, other: $t) -> bool {
70                divisible_by_signed(self, other)
71            }
72        }
73    };
74}
75apply_to_signeds!(impl_divisible_by_signed);