Skip to main content

malachite_nz/integer/arithmetic/
parity.rs

1// Copyright © 2026 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::integer::Integer;
10use malachite_base::num::arithmetic::traits::Parity;
11
12impl Parity for &Integer {
13    /// Tests whether an [`Integer`] is even.
14    ///
15    /// $f(x) = (2|x)$.
16    ///
17    /// $f(x) = (\exists k \in \N : x = 2k)$.
18    ///
19    /// # Worst-case complexity
20    /// Constant time and additional memory.
21    ///
22    /// # Examples
23    /// ```
24    /// use malachite_base::num::arithmetic::traits::{Parity, Pow};
25    /// use malachite_base::num::basic::traits::{One, Zero};
26    /// use malachite_nz::integer::Integer;
27    ///
28    /// assert_eq!(Integer::ZERO.even(), true);
29    /// assert_eq!(Integer::from(123).even(), false);
30    /// assert_eq!(Integer::from(-0x80).even(), true);
31    /// assert_eq!(Integer::from(10u32).pow(12).even(), true);
32    /// assert_eq!((-Integer::from(10u32).pow(12) - Integer::ONE).even(), false);
33    /// ```
34    #[inline]
35    fn even(self) -> bool {
36        self.abs.even()
37    }
38
39    /// Tests whether an [`Integer`] is odd.
40    ///
41    /// $f(x) = (2\nmid x)$.
42    ///
43    /// $f(x) = (\exists k \in \N : x = 2k+1)$.
44    ///
45    /// # Worst-case complexity
46    /// Constant time and additional memory.
47    ///
48    /// # Examples
49    /// ```
50    /// use malachite_base::num::arithmetic::traits::{Parity, Pow};
51    /// use malachite_base::num::basic::traits::{One, Zero};
52    /// use malachite_nz::integer::Integer;
53    ///
54    /// assert_eq!(Integer::ZERO.odd(), false);
55    /// assert_eq!(Integer::from(123).odd(), true);
56    /// assert_eq!(Integer::from(-0x80).odd(), false);
57    /// assert_eq!(Integer::from(10u32).pow(12).odd(), false);
58    /// assert_eq!((-Integer::from(10u32).pow(12) - Integer::ONE).odd(), true);
59    /// ```
60    #[inline]
61    fn odd(self) -> bool {
62        self.abs.odd()
63    }
64}