malachite_nz/lib.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
9//! This crate defines [`Natural`](natural::Natural)s (non-negative integers) and
10//! [`Integer`](integer::Integer)s. Unlike primitive integers ([`u32`], [`i32`], and so on), these
11//! may be arbitrarily large. The name of this crate refers to the mathematical symbols for natural
12//! numbers and integers, $\N$ and $\Z$.
13//! - There are many functions defined on [`Natural`](natural::Natural)s and
14//! [`Integer`](integer::Integer)s. These include
15//! - All the ones you'd expect, like addition, subtraction, multiplication, and integer
16//! division;
17//! - Implementations of [`DivRound`](malachite_base::num::arithmetic::traits::DivRound), which
18//! provides division that rounds according to a specified
19//! [`RoundingMode`](malachite_base::rounding_modes::RoundingMode);
20//! - Various mathematical functions, like implementations of
21//! [`FloorSqrt`](malachite_base::num::arithmetic::traits::FloorSqrt) and
22//! [`Gcd`](malachite_base::num::arithmetic::traits::Gcd);
23//! - Modular arithmetic functions, like implementations of
24//! [`ModAdd`](malachite_base::num::arithmetic::traits::ModAdd) and
25//! [`ModPow`](malachite_base::num::arithmetic::traits::ModPow), and of traits for arithmetic
26//! modulo a power of 2, like
27//! [`ModPowerOf2Add`](malachite_base::num::arithmetic::traits::ModPowerOf2Add) and
28//! [`ModPowerOf2Pow`](malachite_base::num::arithmetic::traits::ModPowerOf2Pow);
29//! - Various functions for logic and bit manipulation, like [`BitAnd`](core::ops::BitAnd) and
30//! [`BitAccess`](malachite_base::num::logic::traits::BitAccess).
31//! - The implementations of these functions use high-performance algorithms that work efficiently
32//! for large numbers. For example, multiplication uses the naive quadratic algorithm, or one of
33//! 13 variants of
34//! [Toom-Cook multiplication](https://en.wikipedia.org/wiki/Toom%E2%80%93Cook_multiplication),
35//! or
36//! [Schönhage-Strassen (FFT) multiplication](https://en.wikipedia.org/wiki/Schonhage-Strassen_algorithm),
37//! depending on the input size.
38//! - Small numbers are also handled efficiently. Any [`Natural`](natural::Natural) smaller than
39//! $2^{64}$ does not use any allocated memory, and working with such numbers is almost as fast
40//! as working with primitive integers. As a result, Malachite does not provide implementations
41//! for _e.g._ adding a [`Natural`](natural::Natural) to a [`u64`], since the [`u64`] can be
42//! converted to a [`Natural`](natural::Natural) very cheaply.
43//! - Malachite handles memory intelligently. Consider the problem of adding a 1000-bit
44//! [`Natural`](natural::Natural) and a 500-bit [`Natural`](natural::Natural). If we only have
45//! references to the [`Natural`](natural::Natural)s, then we must allocate new memory for the
46//! result, and this is what the `&Natural + &Natural` implementation does. However, if we can
47//! take the first (larger) [`Natural`](natural::Natural) by value, then we do not need to
48//! allocate any memory (except in the unlikely case of a carry): we can reuse the memory of the
49//! first [`Natural`](natural::Natural) to store the result, and this is what the
50//! `Natural + &Natural` implementation does. On the other hand, if we can only take the second
51//! (smaller) [`Natural`](natural::Natural) by value, then we only have 500 bits of memory
52//! available, which is not enough to store the sum. In this case, the [`Vec`] containing the
53//! smaller [`Natural`](natural::Natural)'s data can be extended to hold 1000 bits, in hopes that
54//! this will be more efficient than allocating 1000 bits in a completely new [`Vec`]. Finally,
55//! if both [`Natural`](natural::Natural)s are taken by value, then the `Natural + Natural`
56//! implementation chooses to reuse the memory of the larger one.
57//!
58//! Now consider what happens when evaluating the expression `&x + &y + &z`, where each
59//! [`Natural`](natural::Natural) has $n$ bits. Malachite must allocate about $n$ bits for the
60//! result, but what about the intermediate sum `&x + &y`? Does Malachite need to allocate
61//! another $n$ bits for that, for a total of $2n$ bits? No! Malachite first allocates $n$ bits
62//! for `&x + &y`, but then that partial sum is taken by _value_ using the `Natural + &Natural`
63//! implementation described above; so those $n$ bits are reused for the final sum.
64//!
65//! # Limbs
66//! Large [`Natural`](natural::Natural)s and [`Integer`](integer::Integer)s store their data as
67//! [`Vec`]s of some primitive type. The elements of these
68//! [`Vec`]s are called "limbs" in GMP terminology, since they're large digits.
69//! By default, the type of a [`Limb`](crate::platform::Limb) is [`u64`], but you can set it to
70//! [`u32`] using the `32_bit_limbs` feature.
71//!
72//! # Complexity conventions
73//! Functions in this crate are documented with worst-case time and additional-memory bounds,
74//! following the conventions described in the `malachite-base`
75//! [docs](https://docs.rs/malachite-base/latest/malachite_base/#complexity-conventions).
76//!
77//! # Demos and benchmarks
78//! This crate comes with a `bin` target that can be used for running demos and benchmarks.
79//! - Almost all of the public functions in this crate have an associated demo. Running a demo
80//! shows you a function's behavior on a large number of inputs. For example, to demo the
81//! [`mod_pow`](malachite_base::num::arithmetic::traits::ModPow::mod_pow) function on
82//! [`Natural`](natural::Natural)s, you can use the following command:
83//! ```text
84//! cargo run --features bin_build --release -- -l 10000 -m exhaustive -d demo_natural_mod_pow
85//! ```
86//! This command uses the `exhaustive` mode, which generates every possible input, generally
87//! starting with the simplest input and progressing to more complex ones. Another mode is
88//! `random`. The `-l` flag specifies how many inputs should be generated.
89//! - You can use a similar command to run benchmarks. The following command benchmarks various
90//! GCD algorithms for [`u64`]s:
91//! ```text
92//! cargo run --features bin_build --release -- -l 1000000 -m random -b \
93//! benchmark_natural_gcd_algorithms -o gcd-bench.gp
94//! ```
95//! or GCD implementations of other libraries:
96//! ```text
97//! cargo run --features bin_build --release -- -l 1000000 -m random -b \
98//! benchmark_natural_gcd_library_comparison -o gcd-bench.gp
99//! ```
100//! This creates a file called gcd-bench.gp. You can use gnuplot to create an SVG from it like
101//! so:
102//! ```text
103//! gnuplot -e "set terminal svg; l \"gcd-bench.gp\"" > gcd-bench.svg
104//! ```
105//!
106//! The list of available demos and benchmarks is not documented anywhere; you must find them by
107//! browsing through
108//! [`bin_util/demo_and_bench`](https://github.com/mhogrefe/malachite/tree/master/malachite-nz/src/bin_util/demo_and_bench).
109//!
110//! # Features
111//! - `32_bit_limbs`: Sets the type of [`Limb`](crate#limbs) to [`u32`] instead of the default,
112//! [`u64`].
113//! - `test_build`: A large proportion of the code in this crate is only used for testing. For a
114//! typical user, building this code would result in an unnecessarily long compilation time and
115//! an unnecessarily large binary. Some of it is also used for testing `malachite-q`, so it can't
116//! just be confined to the `tests` directory. My solution is to only build this code when the
117//! `test_build` feature is enabled. If you want to run unit tests, you must enable `test_build`.
118//! However, doctests don't require it, since they only test the public interface.
119//! - `bin_build`: This feature is used to build the code for demos and benchmarks, which also
120//! takes a long time to build. Enabling this feature also enables `test_build`.
121
122#![cfg_attr(not(feature = "enable_pyo3"), forbid(unsafe_code))]
123#![allow(
124 unstable_name_collisions,
125 clippy::assertions_on_constants,
126 clippy::cognitive_complexity,
127 clippy::many_single_char_names,
128 clippy::range_plus_one,
129 clippy::suspicious_arithmetic_impl,
130 clippy::suspicious_op_assign_impl,
131 clippy::too_many_arguments,
132 clippy::type_complexity,
133 clippy::upper_case_acronyms,
134 clippy::multiple_bound_locations
135)]
136#![warn(
137 clippy::cast_lossless,
138 clippy::comparison_chain,
139 clippy::explicit_into_iter_loop,
140 clippy::explicit_iter_loop,
141 clippy::filter_map_next,
142 clippy::large_digit_groups,
143 clippy::manual_filter_map,
144 clippy::manual_find_map,
145 clippy::map_flatten,
146 clippy::map_unwrap_or,
147 clippy::match_same_arms,
148 clippy::missing_const_for_fn,
149 clippy::mut_mut,
150 clippy::needless_borrow,
151 clippy::needless_continue,
152 clippy::needless_pass_by_value,
153 clippy::print_stdout,
154 clippy::redundant_closure_for_method_calls,
155 clippy::single_match_else,
156 clippy::trait_duplication_in_bounds,
157 clippy::type_repetition_in_bounds,
158 clippy::uninlined_format_args,
159 clippy::unused_self,
160 clippy::if_not_else,
161 clippy::manual_assert,
162 clippy::range_plus_one,
163 clippy::redundant_else,
164 clippy::semicolon_if_nothing_returned,
165 clippy::cloned_instead_of_copied,
166 clippy::flat_map_option,
167 clippy::unnecessary_wraps,
168 clippy::unnested_or_patterns,
169 clippy::use_self,
170 clippy::trivially_copy_pass_by_ref
171)]
172#![cfg_attr(
173 not(any(feature = "test_build", feature = "random", feature = "std")),
174 no_std
175)]
176
177#[macro_use]
178extern crate alloc;
179
180extern crate itertools;
181#[macro_use]
182extern crate malachite_base;
183#[cfg(feature = "serde")]
184#[macro_use]
185extern crate serde;
186
187#[cfg(feature = "test_build")]
188extern crate num;
189#[cfg(feature = "test_build")]
190extern crate rug;
191
192/// Numeric types whose widths depend on whether Malachite is built with 32-bit or 64-bit limbs.
193///
194/// Large [`Natural`](natural::Natural)s and [`Integer`](integer::Integer)s store their data as
195/// [`Vec`]s of [`Limb`](crate::platform::Limb)s (see the [Limbs](crate#limbs) section). By default
196/// [`Limb`](crate::platform::Limb) is [`u64`], but it is [`u32`] when the `32_bit_limbs` feature is
197/// enabled; the other types here scale accordingly.
198#[doc(inline)]
199#[cfg(not(feature = "32_bit_limbs"))]
200pub use crate::platform_64 as platform;
201/// Numeric types whose widths depend on whether Malachite is built with 32-bit or 64-bit limbs.
202///
203/// Large [`Natural`](natural::Natural)s and [`Integer`](integer::Integer)s store their data as
204/// [`Vec`]s of [`Limb`](crate::platform::Limb)s (see the [Limbs](crate#limbs) section). By default
205/// [`Limb`](crate::platform::Limb) is [`u64`], but it is [`u32`] when the `32_bit_limbs` feature is
206/// enabled; the other types here scale accordingly.
207#[doc(inline)]
208#[cfg(feature = "32_bit_limbs")]
209pub use platform_32 as platform;
210
211#[doc(hidden)]
212#[cfg(feature = "32_bit_limbs")]
213pub mod platform_32;
214#[doc(hidden)]
215#[cfg(not(feature = "32_bit_limbs"))]
216pub mod platform_64;
217
218#[macro_use]
219mod macros;
220
221#[cfg(feature = "doc-images")]
222extern crate embed_doc_image;
223
224/// [`Natural`](natural::Natural), a type representing arbitrarily large non-negative integers.
225#[macro_use]
226pub mod natural;
227/// [`GaussianInteger`](gaussian_integer::GaussianInteger), a type representing complex numbers
228/// whose real and imaginary parts are both integers.
229pub mod gaussian_integer;
230/// [`Integer`](integer::Integer), a type representing integers with arbitrarily large absolute
231/// values.
232#[macro_use]
233pub mod integer;
234/// [`IntegerPolynomial`](integer_polynomial::IntegerPolynomial), a type representing polynomials in
235/// one variable whose coefficients are [`Integer`](integer::Integer)s.
236pub mod integer_polynomial;
237/// [`NaturalPolynomial`](natural_polynomial::NaturalPolynomial), a type representing polynomials in
238/// one variable whose coefficients are [`Natural`](natural::Natural)s.
239pub mod natural_polynomial;
240
241#[cfg(feature = "test_build")]
242pub mod test_util;