Skip to main content

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