malachite_nz/integer/arithmetic/parity.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::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 fn even(self) -> bool {
35 self.abs.even()
36 }
37
38 /// Tests whether an [`Integer`] is odd.
39 ///
40 /// $f(x) = (2\nmid x)$.
41 ///
42 /// $f(x) = (\exists k \in \N : x = 2k+1)$.
43 ///
44 /// # Worst-case complexity
45 /// Constant time and additional memory.
46 ///
47 /// # Examples
48 /// ```
49 /// use malachite_base::num::arithmetic::traits::{Parity, Pow};
50 /// use malachite_base::num::basic::traits::{One, Zero};
51 /// use malachite_nz::integer::Integer;
52 ///
53 /// assert_eq!(Integer::ZERO.odd(), false);
54 /// assert_eq!(Integer::from(123).odd(), true);
55 /// assert_eq!(Integer::from(-0x80).odd(), false);
56 /// assert_eq!(Integer::from(10u32).pow(12).odd(), false);
57 /// assert_eq!((-Integer::from(10u32).pow(12) - Integer::ONE).odd(), true);
58 /// ```
59 fn odd(self) -> bool {
60 self.abs.odd()
61 }
62}