1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
use num::arithmetic::traits::DivisibleBy;
use num::basic::signeds::PrimitiveSigned;
use num::basic::unsigneds::PrimitiveUnsigned;
fn divisible_by_unsigned<T: PrimitiveUnsigned>(x: T, other: T) -> bool {
x == T::ZERO || other != T::ZERO && x % other == T::ZERO
}
macro_rules! impl_divisible_by_unsigned {
($t:ident) => {
impl DivisibleBy<$t> for $t {
/// Returns whether a number is divisible by another number; in other words, whether
/// the first number is a multiple of the second.
///
/// This means that zero is divisible by any number, including zero; but a nonzero
/// number is never divisible by zero.
///
/// $f(x, m) = (m|x)$.
///
/// $f(x, m) = (\exists k \in \N : x = km)$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See [here](super::divisible_by#divisible_by).
#[inline]
fn divisible_by(self, other: $t) -> bool {
divisible_by_unsigned(self, other)
}
}
};
}
apply_to_unsigneds!(impl_divisible_by_unsigned);
fn divisible_by_signed<T: PrimitiveSigned>(x: T, other: T) -> bool {
x == T::ZERO
|| x == T::MIN && other == T::NEGATIVE_ONE
|| other != T::ZERO && x % other == T::ZERO
}
macro_rules! impl_divisible_by_signed {
($t:ident) => {
impl DivisibleBy<$t> for $t {
/// Returns whether a number is divisible by another number; in other words, whether
/// the first number is a multiple of the second.
///
/// This means that zero is divisible by any number, including zero; but a nonzero
/// number is never divisible by zero.
///
/// $f(x, m) = (m|x)$.
///
/// $f(x, m) = (\exists k \in \Z : \ x = km)$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See [here](super::divisible_by#divisible_by).
#[inline]
fn divisible_by(self, other: $t) -> bool {
divisible_by_signed(self, other)
}
}
};
}
apply_to_signeds!(impl_divisible_by_signed);