malachite_nz/natural/arithmetic/neg.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// Uses code adopted from the GNU MP Library.
4//
5// Copyright © 1991, 1993-1997, 1999-2016, 2020 Free Software Foundation, Inc.
6//
7// This file is part of Malachite.
8//
9// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
10// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
11// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
12
13use crate::integer::Integer;
14use crate::natural::Natural;
15use crate::natural::logic::not::limbs_not_in_place;
16use crate::platform::Limb;
17use core::ops::Neg;
18use malachite_base::num::arithmetic::traits::WrappingNegAssign;
19use malachite_base::slices::slice_leading_zeros;
20
21// This is equivalent to `mpn_neg` from `gmp.h`, GMP 6.2.1, where rp == up.
22pub(crate) fn limbs_neg_in_place(xs: &mut [Limb]) -> bool {
23 let n = xs.len();
24 let zeros = slice_leading_zeros(xs);
25 if zeros == n {
26 return false;
27 }
28 xs[zeros].wrapping_neg_assign();
29 let offset = zeros + 1;
30 if offset != n {
31 limbs_not_in_place(&mut xs[offset..]);
32 }
33 true
34}
35
36impl Neg for Natural {
37 type Output = Integer;
38
39 /// Negates a [`Natural`], taking it by value and returning an [`Integer`].
40 ///
41 /// $$
42 /// f(x) = -x.
43 /// $$
44 ///
45 /// # Worst-case complexity
46 /// Constant time and additional memory.
47 ///
48 /// # Examples
49 /// ```
50 /// use malachite_base::num::basic::traits::Zero;
51 /// use malachite_nz::natural::Natural;
52 ///
53 /// assert_eq!(-Natural::ZERO, 0);
54 /// assert_eq!(-Natural::from(123u32), -123);
55 /// ```
56 fn neg(self) -> Integer {
57 Integer::from_sign_and_abs(self == 0, self)
58 }
59}
60
61impl Neg for &Natural {
62 type Output = Integer;
63
64 /// Negates a [`Natural`], taking it by reference and returning an [`Integer`].
65 ///
66 /// $$
67 /// f(x) = -x.
68 /// $$
69 ///
70 /// # Worst-case complexity
71 /// $T(n) = O(n)$
72 ///
73 /// $M(n) = O(n)$
74 ///
75 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
76 ///
77 /// # Examples
78 /// ```
79 /// use malachite_base::num::basic::traits::Zero;
80 /// use malachite_nz::natural::Natural;
81 ///
82 /// assert_eq!(-&Natural::ZERO, 0);
83 /// assert_eq!(-&Natural::from(123u32), -123);
84 /// ```
85 fn neg(self) -> Integer {
86 Integer::from_sign_and_abs_ref(*self == 0, self)
87 }
88}