Skip to main content

malachite_base/num/arithmetic/
traits.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::num::basic::traits::Two;
10use crate::rounding_modes::RoundingMode;
11use core::cmp::Ordering;
12
13/// Takes the absolute value of a number. Assumes that the number has a representable absolute
14/// value.
15pub trait Abs {
16    type Output;
17
18    fn abs(self) -> Self::Output;
19}
20
21/// Replaces a number with its absolute value. Assumes that the number has a representable absolute
22/// value.
23pub trait AbsAssign {
24    fn abs_assign(&mut self);
25}
26
27/// Computes the squared absolute value of a number.
28///
29/// For a real number this is just its square, but for a complex number it is the sum of the squares
30/// of its real and imaginary parts. In both cases it equals $|x|^2$; for Gaussian integers and
31/// Gaussian rationals this quantity is also called the norm.
32pub trait AbsSquared {
33    type Output;
34
35    fn abs_squared(self) -> Self::Output;
36}
37
38/// Replaces a number with its squared absolute value.
39///
40/// For a real number this is just squaring in place. For a complex number the result is the purely
41/// real value $|x|^2$, embedded in the same type.
42pub trait AbsSquaredAssign {
43    fn abs_squared_assign(&mut self);
44}
45
46/// Computes the complex conjugate of a number.
47///
48/// For a complex number the sign of the imaginary part is flipped. For a real number, which is its
49/// own conjugate, this is the identity; the trivial implementations let generic code use
50/// conjugation uniformly, for example when forming Hermitian products.
51pub trait Conjugate {
52    type Output;
53
54    fn conjugate(self) -> Self::Output;
55}
56
57/// Replaces a number with its complex conjugate.
58///
59/// For a complex number the sign of the imaginary part is flipped. For a real number this does
60/// nothing.
61pub trait ConjugateAssign {
62    fn conjugate_assign(&mut self);
63}
64
65/// Multiplies a number by $i$, the imaginary unit.
66///
67/// For a complex number $a + bi$ this is $-b + ai$, a counterclockwise quarter turn. No type in
68/// this crate implements this trait; it exists for complex types downstream, like Gaussian
69/// integers.
70pub trait MulI {
71    type Output;
72
73    fn mul_i(self) -> Self::Output;
74}
75
76/// Replaces a number with its product with $i$, the imaginary unit.
77///
78/// For a complex number $a + bi$ the result is $-b + ai$, a counterclockwise quarter turn. No type
79/// in this crate implements this trait; it exists for complex types downstream, like Gaussian
80/// integers.
81pub trait MulIAssign {
82    fn mul_i_assign(&mut self);
83}
84
85/// Divides a number by $i$, the imaginary unit.
86///
87/// For a complex number $a + bi$ this is $b - ai$, a clockwise quarter turn. No type in this crate
88/// implements this trait; it exists for complex types downstream, like Gaussian integers.
89pub trait DivI {
90    type Output;
91
92    fn div_i(self) -> Self::Output;
93}
94
95/// Replaces a number with its quotient by $i$, the imaginary unit.
96///
97/// For a complex number $a + bi$ the result is $b - ai$, a clockwise quarter turn. No type in this
98/// crate implements this trait; it exists for complex types downstream, like Gaussian integers.
99pub trait DivIAssign {
100    fn div_i_assign(&mut self);
101}
102
103/// Multiplies a number by $i^k$, a power of the imaginary unit.
104///
105/// Only $k$ modulo 4 matters: $i^0 = 1$, $i^1 = i$, $i^2 = -1$, and $i^3 = -i$, so the result is
106/// the number itself, a counterclockwise quarter turn, a half turn, or a clockwise quarter turn.
107/// Since $i^{-k} = i^{3k}$, a negative power is a matter of tripling the exponent. No type in this
108/// crate implements this trait; it exists for complex types downstream, like Gaussian integers.
109pub trait MulIPow {
110    type Output;
111
112    fn mul_i_pow(self, k: u64) -> Self::Output;
113}
114
115/// Replaces a number with its product with $i^k$, a power of the imaginary unit.
116///
117/// Only $k$ modulo 4 matters: $i^0 = 1$, $i^1 = i$, $i^2 = -1$, and $i^3 = -i$, so the result is
118/// the number itself, a counterclockwise quarter turn, a half turn, or a clockwise quarter turn.
119/// Since $i^{-k} = i^{3k}$, a negative power is a matter of tripling the exponent. No type in this
120/// crate implements this trait; it exists for complex types downstream, like Gaussian integers.
121pub trait MulIPowAssign {
122    fn mul_i_pow_assign(&mut self, k: u64);
123}
124
125/// Determines whether a number is a unit of its ring, meaning that it has a multiplicative inverse
126/// in the same ring.
127///
128/// Which elements these are depends on the ring: the only unit of $\mathbb{N}$ is 1, the units of
129/// $\mathbb{Z}$ are $\pm 1$, the Gaussian integers have four, $\pm 1$ and $\pm i$, and in a field
130/// every nonzero element is a unit.
131///
132/// The implementations for the primitive integers follow suit, and the ones for the primitive
133/// floats count every finite nonzero value.
134pub trait IsUnit {
135    fn is_unit(&self) -> bool;
136}
137
138/// Finds the power of $i$ that brings a number into canonical Gaussian-unit form.
139///
140/// The Gaussian units are $1$, $i$, $-1$, and $-i$: the units of the Gaussian integers. Multiplying
141/// a nonzero complex number by them gives its four Gaussian associates, $x$, $ix$, $-x$, and $-ix$,
142/// and the canonical one is the one whose argument lies in $(-\pi/4, \pi/4]$, meaning that its real
143/// part $a$ is positive and its imaginary part $b$ satisfies $-a < b \leq a$. This function returns
144/// the $k \in \\{0, 1, 2, 3\\}$ such that $x i^k$ is canonical, and 0 for zero;
145/// [`CanonicalizeGaussianUnit`] does the multiplication.
146///
147/// A real number has only the two Gaussian associates $\pm x$ to choose between, so the answer
148/// there is 0 for a nonnegative number and 2 for a negative one, $i^2$ being $-1$. That is what the
149/// primitive implementations return.
150///
151/// This is the canonical form of [`CanonicalizeUnit`] only when the ring's units are Gaussian
152/// units: for the integers, whose units are $\pm 1$, and the Gaussian integers, whose units are
153/// $\pm 1$ and $\pm i$. In a field every nonzero element is a unit, so the canonical associate of a
154/// nonzero rational or Gaussian rational is 1, which no power of $i$ reaches.
155pub trait CanonicalUnitIPow {
156    fn canonical_unit_i_pow(&self) -> u64;
157}
158
159/// Brings a number into canonical unit form: replaces it with its canonical associate.
160///
161/// The associates of a number are the numbers it becomes when multiplied by a unit of its ring, and
162/// the canonical associate is the one chosen to represent them all. Each implementation documents
163/// its choice. An unsigned number is already canonical, so the unsigned implementations are the
164/// identity; the units of the integers are $\pm 1$, so the signed implementations return the
165/// absolute value; the units of the Gaussian integers are the powers of $i$, and the canonical
166/// associate is the one whose argument lies in $(-\pi/4, \pi/4]$ (see [`CanonicalUnitIPow`]). In a
167/// field every nonzero element is a unit, so the canonical associate of a nonzero rational number,
168/// a nonzero Gaussian rational, or a finite nonzero floating-point number is 1; zero, the
169/// infinities, and NaN are not units, and keep their absolute value. For a polynomial over the
170/// integers it is the associate with a positive leading coefficient, and over the rationals it is
171/// the monic one.
172///
173/// For the canonical form under the Gaussian units $\pm 1$ and $\pm i$ alone, which rotates a
174/// number by a power of $i$ rather than collapsing a field's units to 1, see
175/// [`CanonicalizeGaussianUnit`].
176pub trait CanonicalizeUnit {
177    type Output;
178
179    fn canonicalize_unit(self) -> Self::Output;
180}
181
182/// Replaces a number with its canonical unit form: its canonical associate.
183///
184/// This is the in-place form of [`CanonicalizeUnit`], and the same per-type behaviour applies.
185pub trait CanonicalizeUnitAssign {
186    fn canonicalize_unit_assign(&mut self);
187}
188
189/// Brings a number into canonical Gaussian-unit form: multiplies it by the power of $i$ that
190/// [`CanonicalUnitIPow`] finds.
191///
192/// The result is the Gaussian associate whose argument lies in $(-\pi/4, \pi/4]$. For a real number
193/// that is its absolute value, and zero is its own canonical form. This differs from
194/// [`CanonicalizeUnit`] exactly in a field, where every nonzero element is a unit and canonicalizes
195/// to 1; here a nonzero number keeps its magnitude and is only rotated by a quarter turn or
196/// negated.
197pub trait CanonicalizeGaussianUnit {
198    type Output;
199
200    fn canonicalize_gaussian_unit(self) -> Self::Output;
201}
202
203/// Replaces a number with its canonical Gaussian-unit form.
204///
205/// This is the in-place form of [`CanonicalizeGaussianUnit`].
206pub trait CanonicalizeGaussianUnitAssign {
207    fn canonicalize_gaussian_unit_assign(&mut self);
208}
209
210/// Brings a value into canonical sign form: negates it if it is negative, so that the result is
211/// non-negative.
212///
213/// A value and its negation are the same up to multiplication by $\pm 1$, and this picks one of the
214/// two to represent both. What "negative" means is up to the type: a vector is negative when its
215/// pivot, its first nonzero element, is, so a vector of zeros is already canonical.
216pub trait CanonicalizeSign {
217    type Output;
218
219    fn canonicalize_sign(self) -> Self::Output;
220}
221
222/// Replaces a value with its canonical sign form.
223///
224/// This is the in-place form of [`CanonicalizeSign`].
225pub trait CanonicalizeSignAssign {
226    fn canonicalize_sign_assign(&mut self);
227}
228
229/// Takes the absolute value of a number and converts to the unsigned equivalent.
230pub trait UnsignedAbs {
231    type Output;
232
233    fn unsigned_abs(self) -> Self::Output;
234}
235
236/// Replaces every entry of a value, such as every element of a vector, by its absolute value.
237///
238/// This is distinct from [`Abs`], which for a vector would be its Euclidean length.
239pub trait EntrywiseAbs {
240    type Output;
241
242    fn entrywise_abs(self) -> Self::Output;
243}
244
245/// Replaces every entry of a value, such as every element of a vector, by its absolute value, in
246/// place.
247pub trait EntrywiseAbsAssign {
248    fn entrywise_abs_assign(&mut self);
249}
250
251/// Replaces every entry of a value, such as every element of a vector, by its absolute value,
252/// converting to the unsigned equivalent, as [`UnsignedAbs`] does for a single number.
253pub trait EntrywiseUnsignedAbs {
254    type Output;
255
256    fn entrywise_unsigned_abs(self) -> Self::Output;
257}
258
259/// Takes the entrywise maximum of two values, such as two vectors of the same dimension: the value
260/// whose every entry is the larger of the corresponding entries.
261pub trait EntrywiseMax<RHS = Self> {
262    type Output;
263
264    fn entrywise_max(self, other: RHS) -> Self::Output;
265}
266
267/// Replaces a value, such as a vector, by its entrywise maximum with another: every entry becomes
268/// the larger of itself and the corresponding entry of the other value.
269pub trait EntrywiseMaxAssign<RHS = Self> {
270    fn entrywise_max_assign(&mut self, other: RHS);
271}
272
273/// Takes the entrywise minimum of two values, such as two vectors of the same dimension: the value
274/// whose every entry is the smaller of the corresponding entries.
275pub trait EntrywiseMin<RHS = Self> {
276    type Output;
277
278    fn entrywise_min(self, other: RHS) -> Self::Output;
279}
280
281/// Replaces a value, such as a vector, by its entrywise minimum with another: every entry becomes
282/// the smaller of itself and the corresponding entry of the other value.
283pub trait EntrywiseMinAssign<RHS = Self> {
284    fn entrywise_min_assign(&mut self, other: RHS);
285}
286
287/// Divides every entry of a value, such as a vector, by a scalar, rounding each quotient according
288/// to a specified rounding mode.
289///
290/// Unlike [`DivRound`], no [`Ordering`] is returned, since different entries may be rounded in
291/// different directions.
292pub trait EntrywiseDivRound<RHS> {
293    type Output;
294
295    fn entrywise_div_round(self, other: RHS, rm: RoundingMode) -> Self::Output;
296}
297
298/// Divides every entry of a value, such as a vector, by a scalar in place, rounding each quotient
299/// according to a specified rounding mode.
300///
301/// Unlike [`DivRoundAssign`], no [`Ordering`] is returned, since different entries may be rounded
302/// in different directions.
303pub trait EntrywiseDivRoundAssign<RHS> {
304    fn entrywise_div_round_assign(&mut self, other: RHS, rm: RoundingMode);
305}
306
307/// Left-shifts every entry of a value, such as a vector (multiplying it by a power of 2), rounding
308/// each entry according to a specified rounding mode.
309///
310/// Unlike [`ShlRound`], no [`Ordering`] is returned, since different entries may be rounded in
311/// different directions. Rounding might only be necessary if `other` is negative.
312pub trait EntrywiseShlRound<RHS> {
313    type Output;
314
315    fn entrywise_shl_round(self, other: RHS, rm: RoundingMode) -> Self::Output;
316}
317
318/// Left-shifts every entry of a value, such as a vector (multiplying it by a power of 2), in place,
319/// rounding each entry according to a specified rounding mode.
320///
321/// Unlike [`ShlRoundAssign`], no [`Ordering`] is returned, since different entries may be rounded
322/// in different directions. Rounding might only be necessary if `other` is negative.
323pub trait EntrywiseShlRoundAssign<RHS> {
324    fn entrywise_shl_round_assign(&mut self, other: RHS, rm: RoundingMode);
325}
326
327/// Right-shifts every entry of a value, such as a vector (dividing it by a power of 2), rounding
328/// each entry according to a specified rounding mode.
329///
330/// Unlike [`ShrRound`], no [`Ordering`] is returned, since different entries may be rounded in
331/// different directions. Rounding might only be necessary if `other` is positive.
332pub trait EntrywiseShrRound<RHS> {
333    type Output;
334
335    fn entrywise_shr_round(self, other: RHS, rm: RoundingMode) -> Self::Output;
336}
337
338/// Right-shifts every entry of a value, such as a vector (dividing it by a power of 2), in place,
339/// rounding each entry according to a specified rounding mode.
340///
341/// Unlike [`ShrRoundAssign`], no [`Ordering`] is returned, since different entries may be rounded
342/// in different directions. Rounding might only be necessary if `other` is positive.
343pub trait EntrywiseShrRoundAssign<RHS> {
344    fn entrywise_shr_round_assign(&mut self, other: RHS, rm: RoundingMode);
345}
346
347/// Subtracts two numbers and takes the absolute value of the difference.
348pub trait AbsDiff<RHS = Self> {
349    type Output;
350
351    fn abs_diff(self, other: RHS) -> Self::Output;
352}
353
354/// Replaces a number with the absolute value of its difference with another number.
355pub trait AbsDiffAssign<RHS = Self> {
356    fn abs_diff_assign(&mut self, other: RHS);
357}
358
359/// Adds a number and the product of two other numbers.
360///
361/// Depending on the implementing type, the fused operation may compute the same value as the
362/// unfused `self + y * z` more efficiently; or, for types with rounding, it may compute a *more
363/// accurate* value -- the product enters the addition exactly, with a single rounding at the end --
364/// but *less* efficiently, since the exact product must be computed in full. See each
365/// implementation's documentation for which contract it provides.
366pub trait AddMul<Y = Self, Z = Self> {
367    type Output;
368
369    fn add_mul(self, y: Y, z: Z) -> Self::Output;
370}
371
372/// Adds a number and the product of two other numbers, in place.
373///
374/// Depending on the implementing type, the fused operation may compute the same value as the
375/// unfused `*self + y * z` more efficiently; or, for types with rounding, it may compute a *more
376/// accurate* value -- the product enters the addition exactly, with a single rounding at the end --
377/// but *less* efficiently, since the exact product must be computed in full. See each
378/// implementation's documentation for which contract it provides.
379pub trait AddMulAssign<Y = Self, Z = Self> {
380    fn add_mul_assign(&mut self, y: Y, z: Z);
381}
382
383/// Adds a number and the product of two other numbers, shifted left by a number of bits: $x +
384/// yz2^k$.
385pub trait AddMulShl<Y = Self, Z = Self> {
386    type Output;
387
388    fn add_mul_shl(self, y: Y, z: Z, bits: u64) -> Self::Output;
389}
390
391/// Adds the product of two numbers, shifted left by a number of bits, to a number in place: $x
392/// \gets x + yz2^k$.
393pub trait AddMulShlAssign<Y = Self, Z = Self> {
394    fn add_mul_shl_assign(&mut self, y: Y, z: Z, bits: u64);
395}
396
397/// Adds the products of two pairs of numbers.
398pub trait MulAddMul<Y = Self, Z = Self, W = Self> {
399    type Output;
400
401    fn mul_add_mul(self, y: Y, z: Z, w: W) -> Self::Output;
402}
403
404/// Adds the products of two pairs of numbers, in place.
405pub trait MulAddMulAssign<Y = Self, Z = Self, W = Self> {
406    fn mul_add_mul_assign(&mut self, y: Y, z: Z, w: W);
407}
408
409/// Multiplies two numbers and right-shifts the product (divides it by a power of 2), rounding the
410/// result according to a specified rounding mode. An [`Ordering`] is also returned, indicating
411/// whether the returned value is less than, equal to, or greater than the exact value.
412///
413/// The product is computed exactly, as if at unlimited width; only the final shifted result must be
414/// representable.
415pub trait MulShrRound<RHS = Self, B = u64> {
416    type Output;
417
418    fn mul_shr_round(self, other: RHS, bits: B, rm: RoundingMode) -> (Self::Output, Ordering);
419}
420
421/// Multiplies two numbers and right-shifts the product (divides it by a power of 2) in place,
422/// rounding the result according to a specified rounding mode. An [`Ordering`] is returned,
423/// indicating whether the assigned value is less than, equal to, or greater than the exact value.
424///
425/// The product is computed exactly, as if at unlimited width; only the final shifted result must be
426/// representable.
427pub trait MulShrRoundAssign<RHS = Self, B = u64> {
428    fn mul_shr_round_assign(&mut self, other: RHS, bits: B, rm: RoundingMode) -> Ordering;
429}
430
431/// Subtracts the product of one pair of numbers from the product of another.
432pub trait MulSubMul<Y = Self, Z = Self, W = Self> {
433    type Output;
434
435    fn mul_sub_mul(self, y: Y, z: Z, w: W) -> Self::Output;
436}
437
438/// Subtracts the product of one pair of numbers from the product of another, in place.
439pub trait MulSubMulAssign<Y = Self, Z = Self, W = Self> {
440    fn mul_sub_mul_assign(&mut self, y: Y, z: Z, w: W);
441}
442
443/// Calculates the AGM (arithmetic-geometric mean) of two numbers.
444pub trait Agm<RHS = Self> {
445    type Output;
446
447    fn agm(self, other: RHS) -> Self::Output;
448}
449
450/// Replaces a number with the AGM (arithmetic-geometric mean) of it and another number.
451pub trait AgmAssign<RHS = Self> {
452    fn agm_assign(&mut self, other: RHS);
453}
454
455/// Calculates the hypotenuse of two numbers, $\sqrt{x^2+y^2}$.
456pub trait Hypot<RHS = Self> {
457    type Output;
458
459    fn hypot(self, other: RHS) -> Self::Output;
460}
461
462/// Replaces a number with the hypotenuse of it and another number.
463pub trait HypotAssign<RHS = Self> {
464    fn hypot_assign(&mut self, other: RHS);
465}
466
467/// Calculates the compound function $(1+x)^n$ of a number $x$.
468pub trait Compound<N> {
469    type Output;
470
471    fn compound(self, n: N) -> Self::Output;
472}
473
474/// Replaces a number $x$ with the compound function $(1+x)^n$.
475pub trait CompoundAssign<N> {
476    fn compound_assign(&mut self, n: N);
477}
478
479/// Left-shifts a number (multiplies it by a power of 2), returning `None` if the result is not
480/// representable.
481pub trait ArithmeticCheckedShl<RHS> {
482    type Output;
483
484    fn arithmetic_checked_shl(self, other: RHS) -> Option<Self::Output>;
485}
486
487/// Right-shifts a number (divides it by a power of 2), returning `None` if the result is not
488/// representable.
489pub trait ArithmeticCheckedShr<RHS> {
490    type Output;
491
492    fn arithmetic_checked_shr(self, other: RHS) -> Option<Self::Output>;
493}
494
495/// Computes the average (arithmetic mean) of two numbers, rounding to the nearest integer. Two-way
496/// ties are broken by rounding to the even integer.
497///
498/// The average is computed without overflow: the result is always exact or within a half of the
499/// exact value, so it always fits in the same type as the inputs.
500pub trait Average<RHS = Self> {
501    type Output;
502
503    fn average(self, other: RHS) -> Self::Output;
504}
505
506/// Computes the average (arithmetic mean) of two numbers, rounding to the nearest integer and
507/// replacing the first number with it. Two-way ties are broken by rounding to the even integer.
508///
509/// The average is computed without overflow: the result is always exact or within a half of the
510/// exact value, so it always fits in the same type as the inputs.
511pub trait AverageAssign<RHS = Self> {
512    fn average_assign(&mut self, other: RHS);
513}
514
515/// Computes the average (arithmetic mean) of two numbers and rounds according to a specified
516/// rounding mode. An [`Ordering`] is also returned, indicating whether the returned value is less
517/// than, equal to, or greater than the exact value.
518///
519/// The average is computed without overflow: the result is always exact or within a half of the
520/// exact value, so it always fits in the same type as the inputs.
521pub trait AverageRound<RHS = Self> {
522    type Output;
523
524    fn average_round(self, other: RHS, rm: RoundingMode) -> (Self::Output, Ordering);
525}
526
527/// Computes the average (arithmetic mean) of two numbers, rounding according to a specified
528/// rounding mode and replacing the first number with it. An [`Ordering`] is returned, indicating
529/// whether the assigned value is less than, equal to, or greater than the exact value.
530///
531/// The average is computed without overflow: the result is always exact or within a half of the
532/// exact value, so it always fits in the same type as the inputs.
533pub trait AverageRoundAssign<RHS = Self> {
534    fn average_round_assign(&mut self, other: RHS, rm: RoundingMode) -> Ordering;
535}
536
537pub trait BinomialCoefficient<T = Self> {
538    fn binomial_coefficient(n: T, k: T) -> Self;
539}
540
541pub trait CheckedBinomialCoefficient<T = Self>: Sized {
542    fn checked_binomial_coefficient(n: T, k: T) -> Option<Self>;
543}
544
545/// Takes the ceiling of a number.
546pub trait Ceiling {
547    type Output;
548
549    fn ceiling(self) -> Self::Output;
550}
551
552/// Replaces a number with its ceiling.
553pub trait CeilingAssign {
554    fn ceiling_assign(&mut self);
555}
556
557/// Takes the absolute valie of a number, returning `None` if the result is not representable.
558pub trait CheckedAbs {
559    type Output;
560
561    fn checked_abs(self) -> Option<Self::Output>;
562}
563
564/// Adds two numbers, returning `None` if the result is not representable.
565pub trait CheckedAdd<RHS = Self> {
566    type Output;
567
568    fn checked_add(self, other: RHS) -> Option<Self::Output>;
569}
570
571/// Adds a number and the product of two other numbers, returning `None` if the result is not
572/// representable.
573pub trait CheckedAddMul<Y = Self, Z = Self> {
574    type Output;
575
576    fn checked_add_mul(self, y: Y, z: Z) -> Option<Self::Output>;
577}
578
579/// Adds the products of two pairs of numbers, returning `None` if the result is not representable.
580pub trait CheckedMulAddMul<Y = Self, Z = Self, W = Self> {
581    type Output;
582
583    fn checked_mul_add_mul(self, y: Y, z: Z, w: W) -> Option<Self::Output>;
584}
585
586/// Subtracts the product of one pair of numbers from the product of another, returning `None` if
587/// the result is not representable.
588pub trait CheckedMulSubMul<Y = Self, Z = Self, W = Self> {
589    type Output;
590
591    fn checked_mul_sub_mul(self, y: Y, z: Z, w: W) -> Option<Self::Output>;
592}
593
594/// Divides two numbers, returning `None` if the result is not representable.
595pub trait CheckedDiv<RHS = Self> {
596    type Output;
597
598    fn checked_div(self, other: RHS) -> Option<Self::Output>;
599}
600
601/// Multiplies two numbers, returning `None` if the result is not representable.
602pub trait CheckedMul<RHS = Self> {
603    type Output;
604
605    fn checked_mul(self, other: RHS) -> Option<Self::Output>;
606}
607
608/// Negates a number, returning `None` if the result is not representable.
609pub trait CheckedNeg {
610    type Output;
611
612    fn checked_neg(self) -> Option<Self::Output>;
613}
614
615/// Finds the smallest integer power of 2 greater than or equal to a number, returning `None` if the
616/// result is not representable.
617pub trait CheckedNextPowerOf2 {
618    type Output;
619
620    fn checked_next_power_of_2(self) -> Option<Self::Output>;
621}
622
623/// Raises a number to a power, returning `None` if the result is not representable.
624pub trait CheckedPow<RHS> {
625    type Output;
626
627    fn checked_pow(self, exp: RHS) -> Option<Self::Output>;
628}
629
630/// Squares a number, returning `None` if the result is not representable.
631pub trait CheckedSquare {
632    type Output;
633
634    fn checked_square(self) -> Option<Self::Output>;
635}
636
637/// Subtracts two numbers, returning `None` if the result is not representable.
638pub trait CheckedSub<RHS = Self> {
639    type Output;
640
641    fn checked_sub(self, other: RHS) -> Option<Self::Output>;
642}
643
644/// Subtracts a number by the product of two other numbers, returning `None` if the result is not
645/// representable.
646pub trait CheckedSubMul<Y = Self, Z = Self> {
647    type Output;
648
649    fn checked_sub_mul(self, y: Y, z: Z) -> Option<Self::Output>;
650}
651
652/// Determines whether two numbers are coprime.
653pub trait CoprimeWith<RHS = Self> {
654    fn coprime_with(self, other: RHS) -> bool;
655}
656
657/// Combines two congruences by the Chinese remainder theorem, returning `None` if the moduli are
658/// not coprime. The residues must be already reduced modulo their moduli.
659pub trait Crt<M1 = Self, R2 = Self, M2 = Self> {
660    type Output;
661
662    fn crt(self, m1: M1, r2: R2, m2: M2) -> Option<Self::Output>;
663}
664
665/// Combines two congruences by the Chinese remainder theorem, returning the representative of
666/// smallest absolute value, or `None` if the moduli are not coprime. The first residue may be
667/// negative.
668pub trait BalancedCrt<M1 = Self, R2 = Self, M2 = Self> {
669    type Output;
670
671    fn balanced_crt(self, m1: M1, r2: R2, m2: M2) -> Option<Self::Output>;
672}
673
674/// Divides two numbers, assuming the first exactly divides the second.
675///
676/// If it doesn't, the `div_exact` function may panic or return a meaningless result.
677pub trait DivExact<RHS = Self> {
678    type Output;
679
680    fn div_exact(self, other: RHS) -> Self::Output;
681}
682
683/// Divides a number by another number in place, assuming the first exactly divides the second.
684///
685/// If it doesn't, this function may panic or assign a meaningless number to the first number.
686pub trait DivExactAssign<RHS = Self> {
687    fn div_exact_assign(&mut self, other: RHS);
688}
689
690/// Divides two numbers, returning the quotient and remainder. The quotient is rounded towards
691/// negative infinity, and the remainder has the same sign as the divisor (second input).
692///
693/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq |r| < |y|$.
694pub trait DivMod<RHS = Self> {
695    type DivOutput;
696    type ModOutput;
697
698    fn div_mod(self, other: RHS) -> (Self::DivOutput, Self::ModOutput);
699}
700
701/// Divides two numbers, returning the quotient and remainder. The quotient is rounded towards
702/// negative infinity, and the remainder has the same sign as the divisor (second input).
703///
704/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq |r| < |y|$.
705///
706/// If multiple divisions by the same divisor are necessary, it can be quicker to precompute some
707/// piece of data based on the divisor and reuse it in the division calls. This trait provides a
708/// function for precomputing the data and a function for using it during division.
709pub trait DivModPrecomputed<RHS = Self> {
710    type DivOutput;
711    type ModOutput;
712    type Data;
713
714    /// Precomputes some data to use for division.
715    fn precompute_div_mod_data(other: &RHS) -> Self::Data;
716
717    fn div_mod_precomputed(
718        self,
719        other: RHS,
720        data: &Self::Data,
721    ) -> (Self::DivOutput, Self::ModOutput);
722}
723
724/// Divides a number by another number in place, returning the remainder. The quotient is rounded
725/// towards negative infinity, and the remainder has the same sign as the divisor (second input).
726///
727/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq |r| < |y|$.
728///
729/// If multiple divisions by the same divisor are necessary, it can be quicker to precompute some
730/// piece of data based on the divisor and reuse it in the division calls. This trait provides a
731/// function for using precomputed data during division. For precomputing the data, use the
732/// [`precompute_div_mod_data`](DivModPrecomputed::precompute_div_mod_data) function in
733/// [`DivModPrecomputed`].
734pub trait DivAssignModPrecomputed<RHS = Self>: DivModPrecomputed<RHS> {
735    fn div_assign_mod_precomputed(&mut self, other: RHS, data: &Self::Data) -> Self::ModOutput;
736}
737
738/// Divides two numbers, returning just the quotient. The quotient is rounded towards the quotient
739/// that makes the remainder nonnegative.
740///
741/// If the remainder were computed, the quotient and remainder would satisfy $x = qy + r$ and $0
742/// \leq r < |y|$.
743pub trait DivEuclidean<RHS = Self> {
744    type Output;
745
746    fn div_euclidean(self, other: RHS) -> Self::Output;
747}
748
749/// Divides a number by another number in place, keeping just the quotient. The quotient is rounded
750/// towards the quotient that makes the remainder nonnegative.
751///
752/// If the remainder were computed, the quotient and remainder would satisfy $x = qy + r$ and $0
753/// \leq r < |y|$.
754pub trait DivEuclideanAssign<RHS = Self> {
755    fn div_euclidean_assign(&mut self, other: RHS);
756}
757
758/// Divides two numbers, returning the quotient and remainder. The quotient is rounded towards the
759/// quotient that makes the remainder nonnegative, and the remainder is always nonnegative.
760///
761/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq r < |y|$.
762pub trait DivModEuclidean<RHS = Self> {
763    type DivOutput;
764    type ModOutput;
765
766    fn div_mod_euclidean(self, other: RHS) -> (Self::DivOutput, Self::ModOutput);
767}
768
769/// Divides a number by another number in place, returning the remainder. The quotient is rounded
770/// towards negative infinity, and the remainder has the same sign as the divisor (second input).
771///
772/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq |r| < |y|$.
773pub trait DivAssignMod<RHS = Self> {
774    type ModOutput;
775
776    fn div_assign_mod(&mut self, other: RHS) -> Self::ModOutput;
777}
778
779/// Divides a number by another number in place, returning the remainder. The quotient is rounded
780/// towards the quotient that makes the remainder nonnegative, and the remainder is always
781/// nonnegative.
782///
783/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq r < |y|$.
784pub trait DivAssignModEuclidean<RHS = Self> {
785    type ModOutput;
786
787    fn div_assign_mod_euclidean(&mut self, other: RHS) -> Self::ModOutput;
788}
789
790/// Divides two numbers, returning the quotient and remainder. The quotient is rounded towards zero,
791/// and the remainder has the same sign as the dividend (first input).
792///
793/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq |r| < |y|$.
794pub trait DivRem<RHS = Self> {
795    type DivOutput;
796    type RemOutput;
797
798    fn div_rem(self, other: RHS) -> (Self::DivOutput, Self::RemOutput);
799}
800
801/// Divides a number by another number in place, returning the remainder. The quotient is rounded
802/// towards zero, and the remainder has the same sign as the dividend (first input).
803///
804/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq |r| < |y|$.
805pub trait DivAssignRem<RHS = Self> {
806    type RemOutput;
807
808    fn div_assign_rem(&mut self, other: RHS) -> Self::RemOutput;
809}
810
811/// Divides a number by another number, returning the ceiling of the quotient and the remainder of
812/// the negative of the first number divided by the second.
813///
814/// The quotient and remainder satisfy $x = qy - r$ and $0 \leq r < y$.
815pub trait CeilingDivNegMod<RHS = Self> {
816    type DivOutput;
817    type ModOutput;
818
819    fn ceiling_div_neg_mod(self, other: RHS) -> (Self::DivOutput, Self::ModOutput);
820}
821
822/// Divides a number by another number in place, taking the ceiling of the quotient and returning
823/// the remainder of the negative of the first number divided by the second.
824///
825/// The quotient and remainder satisfy $x = qy - r$ and $0 \leq r < y$.
826pub trait CeilingDivAssignNegMod<RHS = Self> {
827    type ModOutput;
828
829    fn ceiling_div_assign_neg_mod(&mut self, other: RHS) -> Self::ModOutput;
830}
831
832/// Divides a number by another number, returning the quotient and remainder. The quotient is
833/// rounded towards positive infinity and the remainder has the opposite sign as the divisor (second
834/// input).
835///
836/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq |r| < |y|$.
837pub trait CeilingDivMod<RHS = Self> {
838    type DivOutput;
839    type ModOutput;
840
841    fn ceiling_div_mod(self, other: RHS) -> (Self::DivOutput, Self::ModOutput);
842}
843
844/// Divides a number by another number in place, taking the quotient and returning the remainder.
845/// The quotient is rounded towards positive infinity and the remainder has the opposite sign of the
846/// divisor (second input).
847///
848/// The quotient and remainder satisfy $x = qy + r$ and $0 \leq |r| < |y|$.
849pub trait CeilingDivAssignMod<RHS = Self> {
850    type ModOutput;
851
852    fn ceiling_div_assign_mod(&mut self, other: RHS) -> Self::ModOutput;
853}
854
855/// Divides a number by another number and rounds according to a specified rounding mode. An
856/// [`Ordering`] is also returned, indicating whether the returned value is less than, equal to, or
857/// greater than the exact value.
858pub trait DivRound<RHS = Self> {
859    type Output;
860
861    fn div_round(self, other: RHS, rm: RoundingMode) -> (Self::Output, Ordering);
862}
863
864/// Divides a number by another number in place and rounds according to a specified rounding mode.
865/// An [`Ordering`] is returned, indicating whether the assigned value is less than, equal to, or
866/// greater than the exact value.
867pub trait DivRoundAssign<RHS = Self> {
868    fn div_round_assign(&mut self, other: RHS, rm: RoundingMode) -> Ordering;
869}
870
871/// Determines whether a number is divisible by $2^k$.
872pub trait DivisibleByPowerOf2 {
873    fn divisible_by_power_of_2(self, pow: u64) -> bool;
874}
875
876/// Determines whether a number is divisible by another number.
877pub trait DivisibleBy<RHS = Self> {
878    fn divisible_by(self, other: RHS) -> bool;
879}
880
881/// Determines whether a number is equivalent to another number modulo $2^k$.
882pub trait EqModPowerOf2<RHS = Self> {
883    fn eq_mod_power_of_2(self, other: RHS, pow: u64) -> bool;
884}
885
886/// Determines whether a number is equivalent to another number modulo $m$.
887pub trait EqMod<RHS = Self, M = Self> {
888    fn eq_mod(self, other: RHS, m: M) -> bool;
889}
890
891/// Computes the GCD (greatest common divisor) of two numbers $a$ and $b$, and also the coefficients
892/// $x$ and $y$ in Bézout's identity $ax+by=\gcd(a,b)$.
893///
894/// The are infinitely many $x$, $y$ that satisfy the identity, so the full specification is more
895/// detailed:
896///
897/// - $f(0, 0) = (0, 0, 0)$.
898/// - $f(a, ak) = (a, 1, 0)$ if $a > 0$ and $k \neq 1$.
899/// - $f(a, ak) = (-a, -1, 0)$ if $a < 0$ and $k \neq 1$.
900/// - $f(bk, b) = (b, 0, 1)$ if $b > 0$.
901/// - $f(bk, b) = (-b, 0, -1)$ if $b < 0$.
902/// - $f(a, b) = (g, x, y)$ if $a \neq 0$ and $b \neq 0$ and $\gcd(a, b) \neq \min(|a|, |b|)$, where
903///   $g = \gcd(a, b) \geq 0$, $ax + by = g$, $x \leq \lfloor b/g \rfloor$, and $y \leq \lfloor a/g
904///   \rfloor$.
905pub trait ExtendedGcd<RHS = Self> {
906    type Gcd;
907    type Cofactor;
908
909    fn extended_gcd(self, other: RHS) -> (Self::Gcd, Self::Cofactor, Self::Cofactor);
910}
911
912/// Computes the $n$th Bell number: the number of ways to partition a set of $n$ elements.
913pub trait BellNumber {
914    fn bell_number(n: u64) -> Self;
915}
916
917/// Computes the $n$th Bell number, returning `None` if the result is too large to be represented.
918pub trait CheckedBellNumber: Sized {
919    fn checked_bell_number(n: u64) -> Option<Self>;
920}
921
922/// Computes the factorial of a `u64`.
923pub trait Factorial {
924    fn factorial(n: u64) -> Self;
925}
926
927/// Computes the factorial of a `u64`, returning `None` if the result is too large to be
928/// represented.
929pub trait CheckedFactorial: Sized {
930    fn checked_factorial(n: u64) -> Option<Self>;
931}
932
933/// Computes the double factorial of a `u64`. The double factorial of a non-negative integer is the
934/// product of all the positive integers that are less than or equal to it and have the same parity
935/// as it.
936pub trait DoubleFactorial {
937    fn double_factorial(n: u64) -> Self;
938}
939
940/// Computes the double factorial of a `u64`, returning `None` if the result is too large to be
941/// represented. The double factorial of a non-negative integer is the product of all the positive
942/// integers that are less than or equal to it and have the same parity as it.
943pub trait CheckedDoubleFactorial: Sized {
944    fn checked_double_factorial(n: u64) -> Option<Self>;
945}
946
947/// Computes the $m$-multifactorial of a `u64`. The $m$-multifactorial of a non-negative integer $n$
948/// is the product of all integers $k$ such that $0<k\leq n$ and $k\equiv n \pmod m$.
949pub trait Multifactorial {
950    fn multifactorial(n: u64, m: u64) -> Self;
951}
952
953/// Computes the $m$-multifactorial of a `u64`, returning `None` if the result is too large to be
954/// represented. The $m$-multifactorial of a non-negative integer $n$ is the product of all integers
955/// $k$ such that $0<k\leq n$ and $k\equiv n \pmod m$.
956pub trait CheckedMultifactorial: Sized {
957    fn checked_multifactorial(n: u64, m: u64) -> Option<Self>;
958}
959
960/// Computes the subfactorial of a `u64`. The subfactorial of a non-negative integer $n$ counts the
961/// number of derangements of $n$ elements, which are the permutations in which no element is fixed.
962pub trait Subfactorial {
963    fn subfactorial(n: u64) -> Self;
964}
965
966/// Computes the subfactorial of a `u64`, returning `None` if the result is too large to be
967/// represented. The subfactorial of a non-negative integer $n$ counts the number of derangements of
968/// $n$ elements, which are the permutations in which no element is fixed.
969pub trait CheckedSubfactorial: Sized {
970    fn checked_subfactorial(n: u64) -> Option<Self>;
971}
972
973/// Computes the rising factorial of a number: the product of the `n` consecutive numbers starting
974/// at `self`, or 1 when `n` is 0.
975pub trait RisingFactorial {
976    type Output;
977
978    fn rising_factorial(self, n: u64) -> Self::Output;
979}
980
981/// Computes the rising factorial of a number, returning `None` if the result cannot be represented.
982pub trait CheckedRisingFactorial: Sized {
983    fn checked_rising_factorial(self, n: u64) -> Option<Self>;
984}
985
986/// Computes the falling factorial of a number: the product of the `n` consecutive numbers counting
987/// down from `self`, or 1 when `n` is 0.
988pub trait FallingFactorial {
989    type Output;
990
991    fn falling_factorial(self, n: u64) -> Self::Output;
992}
993
994/// Computes the falling factorial of a number, returning `None` if the result cannot be
995/// represented.
996pub trait CheckedFallingFactorial: Sized {
997    fn checked_falling_factorial(self, n: u64) -> Option<Self>;
998}
999
1000/// Computes the $n$th Fibonacci number, either alone or paired with its predecessor:
1001/// `fibonacci_pair(n)` returns $(F(n), F(n-1))$.
1002pub trait Fibonacci: Sized {
1003    fn fibonacci(n: u64) -> Self;
1004
1005    fn fibonacci_pair(n: u64) -> (Self, Self);
1006}
1007
1008/// Computes the $n$th Fibonacci number, either alone or paired with its predecessor, returning
1009/// `None` if the result is too large to be represented.
1010pub trait CheckedFibonacci: Sized {
1011    fn checked_fibonacci(n: u64) -> Option<Self>;
1012
1013    fn checked_fibonacci_pair(n: u64) -> Option<(Self, Self)>;
1014}
1015
1016/// Takes the floor of a number.
1017pub trait Floor {
1018    type Output;
1019
1020    fn floor(self) -> Self::Output;
1021}
1022
1023/// Replaces a number with its floor.
1024pub trait FloorAssign {
1025    fn floor_assign(&mut self);
1026}
1027
1028/// Calculates the GCD (greatest common divisor) of two numbers.
1029pub trait Gcd<RHS = Self> {
1030    type Output;
1031
1032    fn gcd(self, other: RHS) -> Self::Output;
1033}
1034
1035/// Replaces a number with the GCD (greatest common divisor) of it and another number.
1036pub trait GcdAssign<RHS = Self> {
1037    fn gcd_assign(&mut self, other: RHS);
1038}
1039
1040/// Calculates the height of a value: the largest of the magnitudes of the parts it is built from.
1041///
1042/// For a rational number $p/q$ in lowest terms this is $\max(|p|, q)$, the measure in which
1043/// Diophantine approximation bounds are usually stated. For something built out of several such
1044/// values — a polynomial, or a complex number — it is the largest of their heights.
1045pub trait Height {
1046    type Output;
1047
1048    fn to_height(&self) -> Self::Output;
1049
1050    fn into_height(self) -> Self::Output;
1051
1052    fn height_significant_bits(&self) -> u64;
1053}
1054
1055/// Lends the height of a value, for the types that already hold it.
1056///
1057/// Most heights are one of the magnitudes the value is built from, so they can be lent rather than
1058/// built: a rational number's height is its numerator or its denominator, and a polynomial's is one
1059/// of its coefficients. This is separate from [`Height`] because not every height is stored — the
1060/// coefficients of a polynomial over the rationals share one denominator, so a coefficient's height
1061/// has to be worked out before it can be compared with the others, and there is nothing to lend.
1062///
1063/// It is also not worth implementing where the height is a primitive integer, since there is no
1064/// clone to avoid.
1065pub trait HeightRef: Height {
1066    fn height_ref(&self) -> &Self::Output;
1067}
1068
1069/// Calculates the $\ell^1$ norm of a value: the sum of the absolute values of the parts it is built
1070/// from, such as the elements of a vector.
1071pub trait L1Norm {
1072    type Output;
1073
1074    fn to_l1_norm(&self) -> Self::Output;
1075
1076    fn into_l1_norm(self) -> Self::Output;
1077
1078    fn l1_norm_significant_bits(&self) -> u64;
1079}
1080
1081/// Calculates the sum of the elements of a vector modulo $2^k$.
1082///
1083/// The elements must already be reduced modulo $2^k$. Unlike [`ModPowerOf2Sum`], which adds vectors
1084/// to each other, this adds up the elements of one vector, producing a single element.
1085pub trait ModPowerOf2ElementSum {
1086    type Output;
1087
1088    fn to_mod_power_of_2_element_sum(&self, pow: u64) -> Self::Output;
1089
1090    fn into_mod_power_of_2_element_sum(self, pow: u64) -> Self::Output;
1091}
1092
1093/// Calculates the sum of the elements of a vector modulo another number $m$.
1094///
1095/// The elements must already be reduced modulo $m$. Unlike [`ModSum`], which adds vectors to each
1096/// other, this adds up the elements of one vector, producing a single element.
1097pub trait ModElementSum<M> {
1098    type Output;
1099
1100    fn to_mod_element_sum(&self, m: M) -> Self::Output;
1101
1102    fn into_mod_element_sum(self, m: M) -> Self::Output;
1103}
1104
1105/// Calculates the product of the elements of a vector as a value of a wider type, so that the
1106/// product cannot overflow.
1107///
1108/// Unlike [`ElementProduct`], whose output has the type of the elements, this produces a `T` that
1109/// can hold any product of them: for example, the product of the elements of an
1110/// [`UnsignedVector<u64>`](crate::unsigned_vector::UnsignedVector) as a `Natural`.
1111pub trait WideningElementProduct<T> {
1112    fn to_widening_element_product(&self) -> T;
1113
1114    fn into_widening_element_product(self) -> T;
1115}
1116
1117/// Calculates the product of the elements of a vector modulo $2^k$.
1118///
1119/// The elements must already be reduced modulo $2^k$. Unlike [`ModPowerOf2Product`], which
1120/// multiplies values from an iterator, this multiplies the elements of one vector, producing a
1121/// single element.
1122pub trait ModPowerOf2ElementProduct {
1123    type Output;
1124
1125    fn to_mod_power_of_2_element_product(&self, pow: u64) -> Self::Output;
1126
1127    fn into_mod_power_of_2_element_product(self, pow: u64) -> Self::Output;
1128}
1129
1130/// Calculates the product of the elements of a vector modulo another number $m$.
1131///
1132/// The elements must already be reduced modulo $m$. Unlike [`ModProduct`], which multiplies values
1133/// from an iterator, this multiplies the elements of one vector, producing a single element.
1134pub trait ModElementProduct<M> {
1135    type Output;
1136
1137    fn to_mod_element_product(&self, m: M) -> Self::Output;
1138
1139    fn into_mod_element_product(self, m: M) -> Self::Output;
1140}
1141
1142/// Computes the dot product of two vectors: the sum of the products of their corresponding
1143/// elements.
1144///
1145/// The vectors must have the same dimension. The dot product of two 0-dimensional vectors is 0.
1146pub trait Dot<RHS = Self> {
1147    type Output;
1148
1149    fn dot(self, other: RHS) -> Self::Output;
1150}
1151
1152/// Determines the sign of the dot product of two vectors, as the ordering of the dot product
1153/// against 0, without computing the dot product when it can be avoided.
1154///
1155/// The vectors must have the same dimension.
1156pub trait DotSign<RHS = Self> {
1157    fn dot_sign(self, other: RHS) -> Ordering;
1158}
1159
1160/// Computes the dot product of two vectors modulo $2^k$. The elements must already be reduced
1161/// modulo $2^k$.
1162pub trait ModPowerOf2Dot<RHS = Self> {
1163    type Output;
1164
1165    fn mod_power_of_2_dot(self, other: RHS, pow: u64) -> Self::Output;
1166}
1167
1168/// Computes the dot product of two vectors modulo another number $m$. The elements must already be
1169/// reduced modulo $m$.
1170pub trait ModDot<RHS = Self, M = Self> {
1171    type Output;
1172
1173    fn mod_dot(self, other: RHS, m: M) -> Self::Output;
1174}
1175
1176/// Calculates the LCM of the elements of a vector.
1177///
1178/// The LCM of the elements of the 0-dimensional vector is 1, and the LCM is 0 if any element is 0.
1179pub trait ElementLcm {
1180    type Output;
1181
1182    fn to_element_lcm(&self) -> Self::Output;
1183
1184    fn into_element_lcm(self) -> Self::Output;
1185}
1186
1187/// Calculates the product of the elements of a vector.
1188///
1189/// Unlike [`Product`](core::iter::Product), which would multiply vectors together, this multiplies
1190/// the elements of one vector, producing a single element.
1191pub trait ElementProduct {
1192    type Output;
1193
1194    fn to_element_product(&self) -> Self::Output;
1195
1196    fn into_element_product(self) -> Self::Output;
1197}
1198
1199/// Calculates the sum of the elements of a vector.
1200///
1201/// Unlike [`Sum`](core::iter::Sum), which adds vectors to each other, this adds up the elements of
1202/// one vector, producing a single element.
1203pub trait ElementSum {
1204    type Output;
1205
1206    fn to_element_sum(&self) -> Self::Output;
1207
1208    fn into_element_sum(self) -> Self::Output;
1209}
1210
1211/// Determines whether a number is an integer power of 2.
1212pub trait IsPowerOf2 {
1213    fn is_power_of_2(&self) -> bool;
1214}
1215
1216/// Calculates the LCM (least common multiple) of two numbers.
1217pub trait Lcm<RHS = Self> {
1218    type Output;
1219
1220    fn lcm(self, other: RHS) -> Self::Output;
1221}
1222
1223/// Replaces a number with the LCM (least common multiple) of it and another number.
1224pub trait LcmAssign<RHS = Self> {
1225    fn lcm_assign(&mut self, other: RHS);
1226}
1227
1228/// Computes the content of a value: the unique non-negative rational $c$ such that the value is $c$
1229/// times an element of the underlying integer lattice with coprime coordinates.
1230///
1231/// This applies to an element of a vector space over the rationals with a distinguished integer
1232/// lattice, like a polynomial, a Gaussian rational, or a vector. For an element of the lattice
1233/// itself, such as a polynomial or vector with integer entries, the content is the GCD of the
1234/// coordinates, a non-negative integer. Zero has content 0.
1235///
1236/// The content does not depend on any choice of sign or unit: [`PrimitivePart`] and
1237/// [`CanonicalPrimitivePart`] both divide by the same content.
1238pub trait Content {
1239    type Output;
1240
1241    fn content(self) -> Self::Output;
1242}
1243
1244/// Computes the GCD of a given value and the content of another: for a vector, the GCD of the value
1245/// and the vector's elements.
1246///
1247/// This makes it possible to accumulate the common content of several values one at a time,
1248/// starting from 0. As with [`Content`], the computation can stop as soon as the GCD reaches 1.
1249pub trait ContentChained<T> {
1250    type Output;
1251
1252    fn content_chained(self, x: T) -> Self::Output;
1253}
1254
1255/// Computes the primitive part of a value: the element of the underlying integer lattice, with
1256/// coprime coordinates, that the value is the [`Content`] times.
1257///
1258/// $$
1259/// x = \operatorname{cont}(x) \operatorname{pp}(x).
1260/// $$
1261///
1262/// No sign or unit is chosen, so the primitive part of $-x$ is the negative of the primitive part
1263/// of $x$. The primitive part of zero is zero. For the representative that is canonical under
1264/// multiplication by units, see [`CanonicalPrimitivePart`].
1265pub trait PrimitivePart {
1266    type Output;
1267
1268    fn primitive_part(self) -> Self::Output;
1269}
1270
1271/// Replaces a value with its primitive part.
1272///
1273/// See [`PrimitivePart`].
1274pub trait PrimitivePartAssign {
1275    fn primitive_part_assign(&mut self);
1276}
1277
1278/// Computes the content and the primitive part of a value together.
1279///
1280/// The primitive part is found by dividing by the content, so computing both at once finds the
1281/// content only once. See [`Content`] and [`PrimitivePart`].
1282pub trait ContentAndPrimitivePart {
1283    type Content;
1284    type PrimitivePart;
1285
1286    fn content_and_primitive_part(self) -> (Self::Content, Self::PrimitivePart);
1287}
1288
1289/// Computes the canonical primitive part of a value: its [`PrimitivePart`], replaced by the
1290/// canonical associate under multiplication by units, as [`CanonicalizeUnit`] chooses it.
1291///
1292/// $$
1293/// x = u \operatorname{cont}(x) \operatorname{cpp}(x),
1294/// $$
1295///
1296/// where $u$ is a unit. Each implementation documents its choice of associate: for a polynomial
1297/// with integer or rational coefficients it is the one with a non-negative leading coefficient, for
1298/// a vector it is the one whose first nonzero element is positive, and for a Gaussian rational it
1299/// is the one whose argument lies in $(-\pi/4, \pi/4]$. Values with no negative coordinates have
1300/// only one associate to choose from, so for them this is the same as [`PrimitivePart`]. The
1301/// canonical primitive part of zero is zero.
1302pub trait CanonicalPrimitivePart {
1303    type Output;
1304
1305    fn canonical_primitive_part(self) -> Self::Output;
1306}
1307
1308/// Replaces a value with its canonical primitive part.
1309///
1310/// See [`CanonicalPrimitivePart`].
1311pub trait CanonicalPrimitivePartAssign {
1312    fn canonical_primitive_part_assign(&mut self);
1313}
1314
1315/// Computes the content and the canonical primitive part of a value together.
1316///
1317/// The canonical primitive part is found by dividing by the content, so computing both at once
1318/// finds the content only once. See [`Content`] and [`CanonicalPrimitivePart`].
1319pub trait ContentAndCanonicalPrimitivePart {
1320    type Content;
1321    type CanonicalPrimitivePart;
1322
1323    fn content_and_canonical_primitive_part(self) -> (Self::Content, Self::CanonicalPrimitivePart);
1324}
1325
1326/// Computes $e^x$, the exponential of a number.
1327pub trait Exp {
1328    type Output;
1329
1330    fn exp(self) -> Self::Output;
1331}
1332
1333/// Replaces a number with its exponential, $e^x$.
1334pub trait ExpAssign {
1335    fn exp_assign(&mut self);
1336}
1337
1338/// Computes $\cos(x)$, the cosine of a number.
1339pub trait Cos {
1340    type Output;
1341
1342    fn cos(self) -> Self::Output;
1343}
1344
1345/// Replaces a number with its cosine, $\cos(x)$.
1346pub trait CosAssign {
1347    fn cos_assign(&mut self);
1348}
1349
1350/// Computes $\sin(x)$, the sine of a number.
1351pub trait Sin {
1352    type Output;
1353
1354    fn sin(self) -> Self::Output;
1355}
1356
1357/// Replaces a number with its sine, $\sin(x)$.
1358pub trait SinAssign {
1359    fn sin_assign(&mut self);
1360}
1361
1362/// Computes $\sin(x)$ and $\cos(x)$, the sine and cosine of a number, together.
1363pub trait SinCos {
1364    type Output;
1365
1366    fn sin_cos(self) -> (Self::Output, Self::Output);
1367}
1368
1369/// Computes $\tan(x)$, the tangent of a number.
1370pub trait Tan {
1371    type Output;
1372
1373    fn tan(self) -> Self::Output;
1374}
1375
1376/// Replaces a number with its tangent, $\tan(x)$.
1377pub trait TanAssign {
1378    fn tan_assign(&mut self);
1379}
1380
1381/// Computes $\sec(x)$, the secant of a number.
1382pub trait Sec {
1383    type Output;
1384
1385    fn sec(self) -> Self::Output;
1386}
1387
1388/// Replaces a number with its secant, $\sec(x)$.
1389pub trait SecAssign {
1390    fn sec_assign(&mut self);
1391}
1392
1393/// Computes $\csc(x)$, the cosecant of a number.
1394pub trait Csc {
1395    type Output;
1396
1397    fn csc(self) -> Self::Output;
1398}
1399
1400/// Replaces a number with its cosecant, $\csc(x)$.
1401pub trait CscAssign {
1402    fn csc_assign(&mut self);
1403}
1404
1405/// Computes $\cot(x)$, the cotangent of a number.
1406pub trait Cot {
1407    type Output;
1408
1409    fn cot(self) -> Self::Output;
1410}
1411
1412/// Replaces a number with its cotangent, $\cot(x)$.
1413pub trait CotAssign {
1414    fn cot_assign(&mut self);
1415}
1416
1417/// Computes $\arctan(x)$, the arctangent of a number.
1418pub trait Atan {
1419    type Output;
1420
1421    fn atan(self) -> Self::Output;
1422}
1423
1424/// Replaces a number with its arctangent, $\arctan(x)$.
1425pub trait AtanAssign {
1426    fn atan_assign(&mut self);
1427}
1428
1429/// Computes $\operatorname{atan2}(y,x)$, the angle of the point $(x,y)$ measured from the positive
1430/// $x$-axis.
1431pub trait Atan2<RHS = Self> {
1432    type Output;
1433
1434    fn atan2(self, other: RHS) -> Self::Output;
1435}
1436
1437/// Replaces a number $y$ with $\operatorname{atan2}(y,x)$, the angle of the point $(x,y)$ measured
1438/// from the positive $x$-axis.
1439pub trait Atan2Assign<RHS = Self> {
1440    fn atan2_assign(&mut self, other: RHS);
1441}
1442
1443/// Computes $\arcsin(x)$, the arcsine of a number.
1444pub trait Asin {
1445    type Output;
1446
1447    fn asin(self) -> Self::Output;
1448}
1449
1450/// Replaces a number with its arcsine, $\arcsin(x)$.
1451pub trait AsinAssign {
1452    fn asin_assign(&mut self);
1453}
1454
1455/// Computes $\arccos(x)$, the arccosine of a number.
1456pub trait Acos {
1457    type Output;
1458
1459    fn acos(self) -> Self::Output;
1460}
1461
1462/// Replaces a number with its arccosine, $\arccos(x)$.
1463pub trait AcosAssign {
1464    fn acos_assign(&mut self);
1465}
1466
1467/// Computes $\operatorname{asec}(x)$, the arcsecant of a number.
1468pub trait Asec {
1469    type Output;
1470
1471    fn asec(self) -> Self::Output;
1472}
1473
1474/// Replaces a number with its arcsecant, $\operatorname{asec}(x)$.
1475pub trait AsecAssign {
1476    fn asec_assign(&mut self);
1477}
1478
1479/// Computes $\operatorname{acsc}(x)$, the arccosecant of a number.
1480pub trait Acsc {
1481    type Output;
1482
1483    fn acsc(self) -> Self::Output;
1484}
1485
1486/// Replaces a number with its arccosecant, $\operatorname{acsc}(x)$.
1487pub trait AcscAssign {
1488    fn acsc_assign(&mut self);
1489}
1490
1491/// Computes $\operatorname{acot}(x)$, the arccotangent of a number.
1492pub trait Acot {
1493    type Output;
1494
1495    fn acot(self) -> Self::Output;
1496}
1497
1498/// Replaces a number with its arccotangent, $\operatorname{acot}(x)$.
1499pub trait AcotAssign {
1500    fn acot_assign(&mut self);
1501}
1502
1503/// Computes $\cosh(x)$, the hyperbolic cosine of a number.
1504pub trait Cosh {
1505    type Output;
1506
1507    fn cosh(self) -> Self::Output;
1508}
1509
1510/// Replaces a number with its hyperbolic cosine, $\cosh(x)$.
1511pub trait CoshAssign {
1512    fn cosh_assign(&mut self);
1513}
1514
1515/// Computes $\sinh(x)$, the hyperbolic sine of a number.
1516pub trait Sinh {
1517    type Output;
1518
1519    fn sinh(self) -> Self::Output;
1520}
1521
1522/// Replaces a number with its hyperbolic sine, $\sinh(x)$.
1523pub trait SinhAssign {
1524    fn sinh_assign(&mut self);
1525}
1526
1527/// Computes $\sinh(x)$ and $\cosh(x)$, the hyperbolic sine and cosine of a number, together.
1528pub trait SinhCosh {
1529    type Output;
1530
1531    fn sinh_cosh(self) -> (Self::Output, Self::Output);
1532}
1533
1534/// Replaces a number with its hyperbolic sine, $\sinh(x)$, and writes its hyperbolic cosine,
1535/// $\cosh(x)$, to a second number.
1536pub trait SinhCoshAssign {
1537    fn sinh_cosh_assign(&mut self, cosh: &mut Self);
1538}
1539
1540/// Computes $\tanh(x)$, the hyperbolic tangent of a number.
1541pub trait Tanh {
1542    type Output;
1543
1544    fn tanh(self) -> Self::Output;
1545}
1546
1547/// Replaces a number with its hyperbolic tangent, $\tanh(x)$.
1548pub trait TanhAssign {
1549    fn tanh_assign(&mut self);
1550}
1551
1552/// Computes $\operatorname{sech}(x)$, the hyperbolic secant of a number.
1553pub trait Sech {
1554    type Output;
1555
1556    fn sech(self) -> Self::Output;
1557}
1558
1559/// Replaces a number with its hyperbolic secant, $\operatorname{sech}(x)$.
1560pub trait SechAssign {
1561    fn sech_assign(&mut self);
1562}
1563
1564/// Computes $\operatorname{csch}(x)$, the hyperbolic cosecant of a number.
1565pub trait Csch {
1566    type Output;
1567
1568    fn csch(self) -> Self::Output;
1569}
1570
1571/// Replaces a number with its hyperbolic cosecant, $\operatorname{csch}(x)$.
1572pub trait CschAssign {
1573    fn csch_assign(&mut self);
1574}
1575
1576/// Computes $\coth(x)$, the hyperbolic cotangent of a number.
1577pub trait Coth {
1578    type Output;
1579
1580    fn coth(self) -> Self::Output;
1581}
1582
1583/// Replaces a number with its hyperbolic cotangent, $\coth(x)$.
1584pub trait CothAssign {
1585    fn coth_assign(&mut self);
1586}
1587
1588/// Computes $\operatorname{asinh}(x)$, the inverse hyperbolic sine of a number.
1589pub trait Asinh {
1590    type Output;
1591
1592    fn asinh(self) -> Self::Output;
1593}
1594
1595/// Replaces a number with its inverse hyperbolic sine, $\operatorname{asinh}(x)$.
1596pub trait AsinhAssign {
1597    fn asinh_assign(&mut self);
1598}
1599
1600/// Computes $\operatorname{acosh}(x)$, the inverse hyperbolic cosine of a number.
1601pub trait Acosh {
1602    type Output;
1603
1604    fn acosh(self) -> Self::Output;
1605}
1606
1607/// Replaces a number with its inverse hyperbolic cosine, $\operatorname{acosh}(x)$.
1608pub trait AcoshAssign {
1609    fn acosh_assign(&mut self);
1610}
1611
1612/// Computes $\operatorname{atanh}(x)$, the inverse hyperbolic tangent of a number.
1613pub trait Atanh {
1614    type Output;
1615
1616    fn atanh(self) -> Self::Output;
1617}
1618
1619/// Replaces a number with its inverse hyperbolic tangent, $\operatorname{atanh}(x)$.
1620pub trait AtanhAssign {
1621    fn atanh_assign(&mut self);
1622}
1623
1624/// Computes $\operatorname{asech}(x)$, the inverse hyperbolic secant of a number.
1625pub trait Asech {
1626    type Output;
1627
1628    fn asech(self) -> Self::Output;
1629}
1630
1631/// Replaces a number with its inverse hyperbolic secant, $\operatorname{asech}(x)$.
1632pub trait AsechAssign {
1633    fn asech_assign(&mut self);
1634}
1635
1636/// Computes $\operatorname{acsch}(x)$, the inverse hyperbolic cosecant of a number.
1637pub trait Acsch {
1638    type Output;
1639
1640    fn acsch(self) -> Self::Output;
1641}
1642
1643/// Replaces a number with its inverse hyperbolic cosecant, $\operatorname{acsch}(x)$.
1644pub trait AcschAssign {
1645    fn acsch_assign(&mut self);
1646}
1647
1648/// Computes $\operatorname{acoth}(x)$, the inverse hyperbolic cotangent of a number.
1649pub trait Acoth {
1650    type Output;
1651
1652    fn acoth(self) -> Self::Output;
1653}
1654
1655/// Replaces a number with its inverse hyperbolic cotangent, $\operatorname{acoth}(x)$.
1656pub trait AcothAssign {
1657    fn acoth_assign(&mut self);
1658}
1659
1660/// Replaces a number with its sine, $\sin(x)$, and writes its cosine, $\cos(x)$, to a second
1661/// number.
1662pub trait SinCosAssign {
1663    fn sin_cos_assign(&mut self, cos: &mut Self);
1664}
1665
1666/// Computes $e^x-1$, the exponential of a number, minus one.
1667pub trait ExpXMinus1 {
1668    type Output;
1669
1670    fn exp_x_minus_1(self) -> Self::Output;
1671}
1672
1673/// Replaces a number $x$ with $e^x-1$.
1674pub trait ExpXMinus1Assign {
1675    fn exp_x_minus_1_assign(&mut self);
1676}
1677
1678/// Computes $2^x-1$, two raised to the power of a number, minus one.
1679pub trait PowerOf2XMinus1 {
1680    type Output;
1681
1682    fn power_of_2_x_minus_1(self) -> Self::Output;
1683}
1684
1685/// Replaces a number $x$ with $2^x-1$.
1686pub trait PowerOf2XMinus1Assign {
1687    fn power_of_2_x_minus_1_assign(&mut self);
1688}
1689
1690/// Computes $10^x-1$, ten raised to the power of a number, minus one.
1691pub trait PowerOf10XMinus1 {
1692    type Output;
1693
1694    fn power_of_10_x_minus_1(self) -> Self::Output;
1695}
1696
1697/// Replaces a number $x$ with $10^x-1$.
1698pub trait PowerOf10XMinus1Assign {
1699    fn power_of_10_x_minus_1_assign(&mut self);
1700}
1701
1702/// Takes the natural logarithm of a number.
1703pub trait Ln {
1704    type Output;
1705
1706    fn ln(self) -> Self::Output;
1707}
1708
1709/// Replaces a number with its natural logarithm.
1710pub trait LnAssign {
1711    fn ln_assign(&mut self);
1712}
1713
1714/// Computes $\ln(1+x)$.
1715pub trait Ln1PlusX {
1716    type Output;
1717
1718    fn ln_1_plus_x(self) -> Self::Output;
1719}
1720
1721/// Replaces a number $x$ by $\ln(1+x)$.
1722pub trait Ln1PlusXAssign {
1723    fn ln_1_plus_x_assign(&mut self);
1724}
1725
1726/// Calculates the LCM (least common multiple) of two numbers, returning `None` if the result is not
1727/// representable.
1728pub trait CheckedLcm<RHS = Self> {
1729    type Output;
1730
1731    fn checked_lcm(self, other: RHS) -> Option<Self::Output>;
1732}
1733
1734/// Calculates the Legendre symbol of two numbers. Typically the implementations will be identical
1735/// to those of [`JacobiSymbol`].
1736pub trait LegendreSymbol<RHS = Self> {
1737    fn legendre_symbol(self, other: RHS) -> i8;
1738}
1739
1740/// Calculates the Jacobi symbol of two numbers.
1741pub trait JacobiSymbol<RHS = Self> {
1742    fn jacobi_symbol(self, other: RHS) -> i8;
1743}
1744
1745/// Calculates the Kronecker symbol of two numbers.
1746pub trait KroneckerSymbol<RHS = Self> {
1747    fn kronecker_symbol(self, other: RHS) -> i8;
1748}
1749
1750/// Calculates the base-$b$ logarithm of a number, or returns `None` if the number is not a perfect
1751/// power of $b$.
1752pub trait CheckedLogBase<B = Self> {
1753    type Output;
1754
1755    fn checked_log_base(self, base: B) -> Option<Self::Output>;
1756}
1757
1758/// Calculates the floor of the base-$b$ logarithm of a number.
1759pub trait FloorLogBase<B = Self> {
1760    type Output;
1761
1762    fn floor_log_base(self, base: B) -> Self::Output;
1763}
1764
1765/// Calculates the ceiling of the base-$b$ logarithm of a number.
1766pub trait CeilingLogBase<B = Self> {
1767    type Output;
1768
1769    fn ceiling_log_base(self, base: B) -> Self::Output;
1770}
1771
1772/// Calculates the base-2 logarithm of a number, or returns `None` if the number is not a perfect
1773/// power of 2.
1774pub trait CheckedLogBase2 {
1775    type Output;
1776
1777    fn checked_log_base_2(self) -> Option<Self::Output>;
1778}
1779
1780/// Calculates the base-2 logarithm of a number.
1781pub trait LogBase2 {
1782    type Output;
1783
1784    fn log_base_2(self) -> Self::Output;
1785}
1786
1787/// Replaces a number with its base-2 logarithm.
1788pub trait LogBase2Assign {
1789    fn log_base_2_assign(&mut self);
1790}
1791
1792/// Calculates the base-10 logarithm of a number, rounding the (generally irrational) result.
1793pub trait LogBase10 {
1794    type Output;
1795
1796    fn log_base_10(self) -> Self::Output;
1797}
1798
1799/// Replaces a number with its base-10 logarithm, rounding the (generally irrational) result.
1800pub trait LogBase10Assign {
1801    fn log_base_10_assign(&mut self);
1802}
1803
1804/// Computes $\log_2(1+x)$.
1805pub trait LogBase2Of1PlusX {
1806    type Output;
1807
1808    fn log_base_2_1_plus_x(self) -> Self::Output;
1809}
1810
1811/// Replaces a number $x$ by $\log_2(1+x)$.
1812pub trait LogBase2Of1PlusXAssign {
1813    fn log_base_2_1_plus_x_assign(&mut self);
1814}
1815
1816/// Computes $\log_{2^k}(1+x)$.
1817pub trait LogBasePowerOf2Of1PlusX<POW> {
1818    type Output;
1819
1820    fn log_base_power_of_2_1_plus_x(self, pow: POW) -> Self::Output;
1821}
1822
1823/// Replaces a number $x$ by $\log_{2^k}(1+x)$.
1824pub trait LogBasePowerOf2Of1PlusXAssign<POW> {
1825    fn log_base_power_of_2_1_plus_x_assign(&mut self, pow: POW);
1826}
1827
1828/// Computes $\log_b(1+x)$ for an integer base $b$.
1829pub trait LogBaseOf1PlusX<B = Self> {
1830    type Output;
1831
1832    fn log_base_1_plus_x(self, base: B) -> Self::Output;
1833}
1834
1835/// Replaces a number $x$ by $\log_b(1+x)$ for an integer base $b$.
1836pub trait LogBaseOf1PlusXAssign<B = Self> {
1837    fn log_base_1_plus_x_assign(&mut self, base: B);
1838}
1839
1840/// Computes $\log_{10}(1+x)$.
1841pub trait LogBase10Of1PlusX {
1842    type Output;
1843
1844    fn log_base_10_1_plus_x(self) -> Self::Output;
1845}
1846
1847/// Replaces a number $x$ by $\log_{10}(1+x)$.
1848pub trait LogBase10Of1PlusXAssign {
1849    fn log_base_10_1_plus_x_assign(&mut self);
1850}
1851
1852/// Calculates the floor of the base-2 logarithm of a number.
1853pub trait FloorLogBase2 {
1854    type Output;
1855
1856    fn floor_log_base_2(self) -> Self::Output;
1857}
1858
1859/// Calculates the ceiling of the base-2 logarithm of a number.
1860pub trait CeilingLogBase2 {
1861    type Output;
1862
1863    fn ceiling_log_base_2(self) -> Self::Output;
1864}
1865
1866/// Calculates the base-$2^k$ logarithm of a number, or returns `None` if the number is not a
1867/// perfect power of $2^k$.
1868pub trait CheckedLogBasePowerOf2<POW> {
1869    type Output;
1870
1871    fn checked_log_base_power_of_2(self, pow: POW) -> Option<Self::Output>;
1872}
1873
1874/// Calculates the floor of the base-$2^k$ logarithm of a number.
1875pub trait FloorLogBasePowerOf2<POW> {
1876    type Output;
1877
1878    fn floor_log_base_power_of_2(self, pow: POW) -> Self::Output;
1879}
1880
1881/// Calculates the ceiling of the base-$2^k$ logarithm of a number.
1882pub trait CeilingLogBasePowerOf2<POW> {
1883    type Output;
1884
1885    fn ceiling_log_base_power_of_2(self, pow: POW) -> Self::Output;
1886}
1887
1888/// Calculates the base-$2^k$ logarithm of a number.
1889pub trait LogBasePowerOf2<POW> {
1890    type Output;
1891
1892    fn log_base_power_of_2(self, pow: POW) -> Self::Output;
1893}
1894
1895/// Replaces a number with its base-$2^k$ logarithm.
1896pub trait LogBasePowerOf2Assign<POW> {
1897    fn log_base_power_of_2_assign(&mut self, pow: POW);
1898}
1899
1900/// Calculates the base-$b$ logarithm of a number, rounding the (generally irrational) result.
1901pub trait LogBase<B = Self> {
1902    type Output;
1903
1904    fn log_base(self, base: B) -> Self::Output;
1905}
1906
1907/// Replaces a number with its base-$b$ logarithm, rounding the (generally irrational) result.
1908pub trait LogBaseAssign<B = Self> {
1909    fn log_base_assign(&mut self, base: B);
1910}
1911
1912/// Computes the $n$th Lucas number, either alone or paired with its predecessor:
1913/// `lucas_number_pair(n)` returns $(L(n), L(n-1))$.
1914pub trait LucasNumber: Sized {
1915    fn lucas_number(n: u64) -> Self;
1916
1917    fn lucas_number_pair(n: u64) -> (Self, Self);
1918}
1919
1920/// Computes the $n$th Lucas number, either alone or paired with its predecessor, returning `None`
1921/// if the result is too large to be represented.
1922pub trait CheckedLucasNumber: Sized {
1923    fn checked_lucas_number(n: u64) -> Option<Self>;
1924
1925    fn checked_lucas_number_pair(n: u64) -> Option<(Self, Self)>;
1926}
1927
1928/// Adds two numbers modulo a third number $m$. The inputs must be already reduced modulo $m$.
1929pub trait ModAdd<RHS = Self, M = Self> {
1930    type Output;
1931
1932    fn mod_add(self, other: RHS, m: M) -> Self::Output;
1933}
1934
1935/// Adds two numbers modulo a third number $m$, in place. The inputs must be already reduced modulo
1936/// $m$.
1937pub trait ModAddAssign<RHS = Self, M = Self> {
1938    fn mod_add_assign(&mut self, other: RHS, m: M);
1939}
1940
1941/// Divides a number by another number modulo a third number $m$, returning `None` if no quotient
1942/// exists. The inputs must be already reduced modulo $m$.
1943///
1944/// If the divisor is not invertible modulo $m$, a quotient may exist without being unique; in that
1945/// case one of the quotients is returned.
1946pub trait ModDiv<RHS = Self, M = Self> {
1947    type Output;
1948
1949    fn mod_div(self, other: RHS, m: M) -> Option<Self::Output>;
1950}
1951
1952/// Finds all quotients of a number and another number modulo a third number $m$, returning `None`
1953/// if no quotient exists. The inputs must be already reduced modulo $m$.
1954///
1955/// The quotients form an arithmetic progression: `Some((start, stride, length))` means that the
1956/// quotients are exactly the numbers $\text{start} + \text{stride} \cdot i$ for $0 \leq i <
1957/// \text{length}$, where `start` is the smallest quotient.
1958pub trait ModDivList<RHS = Self, M = Self> {
1959    type Output;
1960
1961    #[allow(clippy::type_complexity)]
1962    fn mod_div_list(self, other: RHS, m: M) -> Option<(Self::Output, Self::Output, Self::Output)>;
1963}
1964
1965/// Finds the multiplicative inverse of a number modulo another number $m$. The input must be
1966/// already reduced modulo $m$.
1967pub trait ModInverse<M = Self> {
1968    type Output;
1969
1970    fn mod_inverse(self, m: M) -> Option<Self::Output>;
1971}
1972
1973/// Checks whether a number is reduced modulo another number $m$.
1974pub trait ModIsReduced<M = Self> {
1975    fn mod_is_reduced(&self, m: &M) -> bool;
1976}
1977
1978/// Multiplies two numbers modulo a third number $m$. The inputs must be already reduced modulo $m$.
1979pub trait ModMul<RHS = Self, M = Self> {
1980    type Output;
1981
1982    fn mod_mul(self, other: RHS, m: M) -> Self::Output;
1983}
1984
1985/// Multiplies two numbers modulo a third number $m$, in place. The inputs must be already reduced
1986/// modulo $m$.
1987pub trait ModMulAssign<RHS = Self, M = Self> {
1988    fn mod_mul_assign(&mut self, other: RHS, m: M);
1989}
1990
1991/// Multiplies two numbers modulo a third number $m$. The inputs must be already reduced modulo $m$.
1992///
1993/// If multiple modular multiplications with the same modulus are necessary, it can be quicker to
1994/// precompute some piece of data and reuse it in the multiplication calls. This trait provides a
1995/// function for precomputing the data and a function for using it during multiplication.
1996pub trait ModMulPrecomputed<RHS = Self, M = Self> {
1997    type Output;
1998    type Data;
1999
2000    /// Precomputes some data to use for modular multiplication.
2001    fn precompute_mod_mul_data(m: &M) -> Self::Data;
2002
2003    fn mod_mul_precomputed(self, other: RHS, m: M, data: &Self::Data) -> Self::Output;
2004}
2005
2006/// Multiplies two numbers modulo a third number $m$, in place.The inputs must be already reduced
2007/// modulo $m$.
2008///
2009/// If multiple modular multiplications with the same modulus are necessary, it can be quicker to
2010/// precompute some piece of data and reuse it in the multiplication calls. This trait provides a
2011/// function for using precomputed data during multiplication. For precomputing the data, use the
2012/// [`precompute_mod_mul_data`](ModMulPrecomputed::precompute_mod_mul_data) function in
2013/// [`ModMulPrecomputed`].
2014pub trait ModMulPrecomputedAssign<RHS = Self, M = Self>: ModMulPrecomputed<RHS, M> {
2015    fn mod_mul_precomputed_assign(&mut self, other: RHS, m: M, data: &Self::Data);
2016}
2017
2018/// Adds a number and the product of two other numbers, modulo a fourth number $m$. All three inputs
2019/// must be already reduced modulo $m$.
2020pub trait ModAddMul<Y = Self, Z = Self, M = Self> {
2021    type Output;
2022
2023    fn mod_add_mul(self, y: Y, z: Z, m: M) -> Self::Output;
2024}
2025
2026/// Adds the product of two numbers to a number modulo a fourth number $m$, in place. All three
2027/// inputs must be already reduced modulo $m$.
2028pub trait ModAddMulAssign<Y = Self, Z = Self, M = Self> {
2029    fn mod_add_mul_assign(&mut self, y: Y, z: Z, m: M);
2030}
2031
2032/// Subtracts the product of two numbers from a number, modulo a fourth number $m$. All three inputs
2033/// must be already reduced modulo $m$.
2034pub trait ModSubMul<Y = Self, Z = Self, M = Self> {
2035    type Output;
2036
2037    fn mod_sub_mul(self, y: Y, z: Z, m: M) -> Self::Output;
2038}
2039
2040/// Subtracts the product of two numbers from a number modulo a fourth number $m$, in place. All
2041/// three inputs must be already reduced modulo $m$.
2042pub trait ModSubMulAssign<Y = Self, Z = Self, M = Self> {
2043    fn mod_sub_mul_assign(&mut self, y: Y, z: Z, m: M);
2044}
2045
2046/// Adds a number and the product of two other numbers, shifted left by a number of bits, modulo a
2047/// fourth number $m$: $x + yz2^b \bmod m$. All three inputs must be already reduced modulo $m$.
2048pub trait ModAddMulShl<Y = Self, Z = Self, M = Self> {
2049    type Output;
2050
2051    fn mod_add_mul_shl(self, y: Y, z: Z, bits: u64, m: M) -> Self::Output;
2052}
2053
2054/// Adds the product of two numbers, shifted left by a number of bits, to a number modulo a fourth
2055/// number $m$, in place. All three inputs must be already reduced modulo $m$.
2056pub trait ModAddMulShlAssign<Y = Self, Z = Self, M = Self> {
2057    fn mod_add_mul_shl_assign(&mut self, y: Y, z: Z, bits: u64, m: M);
2058}
2059
2060/// Subtracts the product of two numbers, shifted left by a number of bits, from a number, modulo a
2061/// fourth number $m$: $x - yz2^b \bmod m$. All three inputs must be already reduced modulo $m$.
2062pub trait ModSubMulShl<Y = Self, Z = Self, M = Self> {
2063    type Output;
2064
2065    fn mod_sub_mul_shl(self, y: Y, z: Z, bits: u64, m: M) -> Self::Output;
2066}
2067
2068/// Subtracts the product of two numbers, shifted left by a number of bits, from a number modulo a
2069/// fourth number $m$, in place. All three inputs must be already reduced modulo $m$.
2070pub trait ModSubMulShlAssign<Y = Self, Z = Self, M = Self> {
2071    fn mod_sub_mul_shl_assign(&mut self, y: Y, z: Z, bits: u64, m: M);
2072}
2073
2074/// Adds up the numbers in an iterator, modulo another number $m$. Every number must be already
2075/// reduced modulo $m$.
2076///
2077/// Like [`Sum`](core::iter::Sum), this is implemented both for iterators of values and for
2078/// iterators of references.
2079pub trait ModSum<A = Self, M = Self>: Sized {
2080    fn mod_sum<I: Iterator<Item = A>>(xs: I, m: M) -> Self;
2081}
2082
2083/// Multiplies together the numbers in an iterator, modulo another number $m$. Every number must be
2084/// already reduced modulo $m$.
2085///
2086/// Like [`Product`](core::iter::Product), this is implemented both for iterators of values and for
2087/// iterators of references. The product of no numbers is 1 reduced modulo $m$, which is 0 when $m =
2088/// 1$.
2089pub trait ModProduct<A = Self, M = Self>: Sized {
2090    fn mod_product<I: Iterator<Item = A>>(xs: I, m: M) -> Self;
2091}
2092
2093/// Negates a number modulo another number $m$. The input must be already reduced modulo $m$.
2094pub trait ModNeg<M = Self> {
2095    type Output;
2096
2097    fn mod_neg(self, m: M) -> Self::Output;
2098}
2099
2100/// Negates a number modulo another number $m$, in place. The input must be already reduced modulo
2101/// $m$.
2102pub trait ModNegAssign<M = Self> {
2103    fn mod_neg_assign(&mut self, m: M);
2104}
2105
2106/// Divides a number by another number, returning just the remainder. The remainder has the same
2107/// sign as the divisor (second number).
2108///
2109/// If the quotient were computed, the quotient and remainder would satisfy $x = qy + r$ and $0 \leq
2110/// |r| < |y|$.
2111pub trait Mod<RHS = Self> {
2112    type Output;
2113
2114    fn mod_op(self, other: RHS) -> Self::Output;
2115}
2116
2117/// Divides a number by another number, replacing the first number by the remainder. The remainder
2118/// has the same sign as the divisor (second number).
2119///
2120/// If the quotient were computed, the quotient and remainder would satisfy $x = qy + r$ and $0 \leq
2121/// |r| < |y|$.
2122pub trait ModAssign<RHS = Self> {
2123    fn mod_assign(&mut self, other: RHS);
2124}
2125
2126/// Divides a number by another number, returning the balanced remainder: the representative of the
2127/// first number modulo the second that is closest to zero.
2128///
2129/// The remainder $r$ satisfies $-|y|/2 < r \leq |y|/2$, so a remainder of exactly $|y|/2$ is
2130/// positive. It is congruent to $x$ modulo $y$, and those two properties determine it uniquely.
2131pub trait BalancedMod<RHS = Self> {
2132    type Output;
2133
2134    fn balanced_mod(self, other: RHS) -> Self::Output;
2135}
2136
2137/// Divides a number by another number, replacing the first number by the balanced remainder: the
2138/// representative of the first number modulo the second that is closest to zero.
2139///
2140/// The remainder $r$ satisfies $-|y|/2 < r \leq |y|/2$, so a remainder of exactly $|y|/2$ is
2141/// positive.
2142pub trait BalancedModAssign<RHS = Self> {
2143    fn balanced_mod_assign(&mut self, other: RHS);
2144}
2145
2146/// Divides a number by another number, returning just the remainder. The remainder is always
2147/// nonnegative.
2148///
2149/// If the quotient were computed, the quotient and remainder would satisfy $x = qy + r$ and $0 \leq
2150/// r < |y|$.
2151pub trait ModEuclidean<RHS = Self> {
2152    type Output;
2153
2154    fn mod_euclidean(self, other: RHS) -> Self::Output;
2155}
2156
2157/// Divides a number by another number, replacing the first number by the remainder. The remainder
2158/// is always nonnegative.
2159///
2160/// If the quotient were computed, the quotient and remainder would satisfy $x = qy + r$ and $0 \leq
2161/// r < |y|$.
2162pub trait ModEuclideanAssign<RHS = Self> {
2163    fn mod_euclidean_assign(&mut self, other: RHS);
2164}
2165
2166/// Divides the negative of a number by another number, returning the remainder.
2167///
2168/// If the quotient were computed, the quotient and remainder would satisfy $x = qy - r$ and $0 \leq
2169/// r < y$.
2170pub trait NegMod<RHS = Self> {
2171    type Output;
2172
2173    fn neg_mod(self, other: RHS) -> Self::Output;
2174}
2175
2176/// Divides the negative of a number by another number, replacing the first number by the remainder.
2177///
2178/// If the quotient were computed, the quotient and remainder would satisfy $x = qy - r$ and $0 \leq
2179/// r < y$.
2180pub trait NegModAssign<RHS = Self> {
2181    fn neg_mod_assign(&mut self, other: RHS);
2182}
2183
2184/// Divides a number by another number, returning just the remainder. The remainder has the opposite
2185/// sign as the divisor (second number).
2186///
2187/// If the quotient were computed, the quotient and remainder would satisfy $x = qy + r$ and $0 \leq
2188/// |r| < |y|$.
2189pub trait CeilingMod<RHS = Self> {
2190    type Output;
2191
2192    fn ceiling_mod(self, other: RHS) -> Self::Output;
2193}
2194
2195/// Divides a number by another number, replacing the first number by the remainder. The remainder
2196/// has the same sign as the divisor (second number).
2197///
2198/// If the quotient were computed, the quotient and remainder would satisfy $x = qy + r$ and $0 \leq
2199/// |r| < |y|$.
2200pub trait CeilingModAssign<RHS = Self> {
2201    fn ceiling_mod_assign(&mut self, other: RHS);
2202}
2203
2204/// Raises a number to a power modulo another number $m$. The base must be already reduced modulo
2205/// $m$.
2206pub trait ModPow<RHS = Self, M = Self> {
2207    type Output;
2208
2209    fn mod_pow(self, exp: RHS, m: M) -> Self::Output;
2210}
2211
2212/// Raises a number to a power modulo another number $m$, in place. The base must be already reduced
2213/// modulo $m$.
2214pub trait ModPowAssign<RHS = Self, M = Self> {
2215    fn mod_pow_assign(&mut self, exp: RHS, m: M);
2216}
2217
2218/// Raises a number to a power modulo another number $m$. The base must be already reduced modulo
2219/// $m$.
2220///
2221/// If multiple modular exponentiations with the same modulus are necessary, it can be quicker to
2222/// precompute some piece of data and reuse it in the exponentiation calls. This trait provides a
2223/// function for precomputing the data and a function for using it during exponentiation.
2224pub trait ModPowPrecomputed<RHS = Self, M = Self>
2225where
2226    Self: Sized,
2227{
2228    type Output;
2229    type Data;
2230
2231    /// Precomputes some data to use for modular exponentiation.
2232    fn precompute_mod_pow_data(m: &M) -> Self::Data;
2233
2234    fn mod_pow_precomputed(self, exp: RHS, m: M, data: &Self::Data) -> Self::Output;
2235}
2236
2237/// Raises a number to a power modulo another number $m$, in place. The base must be already reduced
2238/// modulo $m$.
2239///
2240/// If multiple modular exponentiations with the same modulus are necessary, it can be quicker to
2241/// precompute some piece of data and reuse it in the exponentiation calls. This trait provides a
2242/// function for using precomputed data during exponentiation. For precomputing the data, use the
2243/// [`precompute_mod_pow_data`](ModPowPrecomputed::precompute_mod_pow_data) function in
2244/// [`ModPowPrecomputed`].
2245pub trait ModPowPrecomputedAssign<RHS: Two = Self, M = Self>: ModPowPrecomputed<RHS, M> {
2246    fn mod_pow_precomputed_assign(&mut self, exp: RHS, m: M, data: &Self::Data);
2247}
2248
2249/// Adds two numbers modulo $2^k$. The inputs must be already reduced modulo $2^k$.
2250pub trait ModPowerOf2Add<RHS = Self> {
2251    type Output;
2252
2253    fn mod_power_of_2_add(self, other: RHS, pow: u64) -> Self::Output;
2254}
2255
2256/// Adds two numbers modulo $2^k$, in place. The inputs must be already reduced modulo $2^k$.
2257pub trait ModPowerOf2AddAssign<RHS = Self> {
2258    fn mod_power_of_2_add_assign(&mut self, other: RHS, pow: u64);
2259}
2260
2261/// Finds the multiplicative inverse of a number modulo $2^k$. The input must be already reduced
2262/// modulo $2^k$.
2263pub trait ModPowerOf2Inverse {
2264    type Output;
2265
2266    fn mod_power_of_2_inverse(self, pow: u64) -> Option<Self::Output>;
2267}
2268
2269/// Finds the least square root of a number modulo $2^k$, returning `None` if the number is not a
2270/// square modulo $2^k$. The input must be already reduced modulo $2^k$.
2271pub trait ModPowerOf2Sqrt {
2272    type Output;
2273
2274    fn mod_power_of_2_sqrt(self, pow: u64) -> Option<Self::Output>;
2275}
2276
2277/// Checks whether a number is reduced modulo $2^k$.
2278pub trait ModPowerOf2IsReduced {
2279    fn mod_power_of_2_is_reduced(&self, pow: u64) -> bool;
2280}
2281
2282/// Multiplies two numbers modulo $2^k$. The inputs must be already reduced modulo $2^k$.
2283pub trait ModPowerOf2Mul<RHS = Self> {
2284    type Output;
2285
2286    fn mod_power_of_2_mul(self, other: RHS, pow: u64) -> Self::Output;
2287}
2288
2289/// Multiplies two numbers modulo $2^k$, in place. The inputs must be already reduced modulo $2^k$.
2290pub trait ModPowerOf2MulAssign<RHS = Self> {
2291    fn mod_power_of_2_mul_assign(&mut self, other: RHS, pow: u64);
2292}
2293
2294/// Adds a number and the product of two other numbers, modulo $2^k$. All three inputs must be
2295/// already reduced modulo $2^k$.
2296pub trait ModPowerOf2AddMul<Y = Self, Z = Self> {
2297    type Output;
2298
2299    fn mod_power_of_2_add_mul(self, y: Y, z: Z, pow: u64) -> Self::Output;
2300}
2301
2302/// Adds the product of two numbers to a number modulo $2^k$, in place. All three inputs must be
2303/// already reduced modulo $2^k$.
2304pub trait ModPowerOf2AddMulAssign<Y = Self, Z = Self> {
2305    fn mod_power_of_2_add_mul_assign(&mut self, y: Y, z: Z, pow: u64);
2306}
2307
2308/// Adds a number and the product of two other numbers, shifted left by a number of bits, modulo
2309/// $2^k$: $x + yz2^b \bmod 2^k$. All three inputs must be already reduced modulo $2^k$.
2310pub trait ModPowerOf2AddMulShl<Y = Self, Z = Self> {
2311    type Output;
2312
2313    fn mod_power_of_2_add_mul_shl(self, y: Y, z: Z, bits: u64, pow: u64) -> Self::Output;
2314}
2315
2316/// Adds the product of two numbers, shifted left by a number of bits, to a number modulo $2^k$, in
2317/// place. All three inputs must be already reduced modulo $2^k$.
2318pub trait ModPowerOf2AddMulShlAssign<Y = Self, Z = Self> {
2319    fn mod_power_of_2_add_mul_shl_assign(&mut self, y: Y, z: Z, bits: u64, pow: u64);
2320}
2321
2322/// Subtracts the product of two numbers from a number, modulo $2^k$. All three inputs must be
2323/// already reduced modulo $2^k$.
2324pub trait ModPowerOf2SubMul<Y = Self, Z = Self> {
2325    type Output;
2326
2327    fn mod_power_of_2_sub_mul(self, y: Y, z: Z, pow: u64) -> Self::Output;
2328}
2329
2330/// Subtracts the product of two numbers from a number modulo $2^k$, in place. All three inputs must
2331/// be already reduced modulo $2^k$.
2332pub trait ModPowerOf2SubMulAssign<Y = Self, Z = Self> {
2333    fn mod_power_of_2_sub_mul_assign(&mut self, y: Y, z: Z, pow: u64);
2334}
2335
2336/// Subtracts the product of two numbers, shifted left by a number of bits, from a number, modulo
2337/// $2^k$: $x - yz2^b \bmod 2^k$. All three inputs must be already reduced modulo $2^k$.
2338pub trait ModPowerOf2SubMulShl<Y = Self, Z = Self> {
2339    type Output;
2340
2341    fn mod_power_of_2_sub_mul_shl(self, y: Y, z: Z, bits: u64, pow: u64) -> Self::Output;
2342}
2343
2344/// Subtracts the product of two numbers, shifted left by a number of bits, from a number modulo
2345/// $2^k$, in place. All three inputs must be already reduced modulo $2^k$.
2346pub trait ModPowerOf2SubMulShlAssign<Y = Self, Z = Self> {
2347    fn mod_power_of_2_sub_mul_shl_assign(&mut self, y: Y, z: Z, bits: u64, pow: u64);
2348}
2349
2350/// Adds up the numbers in an iterator, modulo $2^k$. Every number must be already reduced modulo
2351/// $2^k$.
2352///
2353/// Like [`Sum`](core::iter::Sum), this is implemented both for iterators of values and for
2354/// iterators of references.
2355pub trait ModPowerOf2Sum<A = Self>: Sized {
2356    fn mod_power_of_2_sum<I: Iterator<Item = A>>(xs: I, pow: u64) -> Self;
2357}
2358
2359/// Multiplies together the numbers in an iterator, modulo $2^k$. Every number must be already
2360/// reduced modulo $2^k$.
2361///
2362/// Like [`Product`](core::iter::Product), this is implemented both for iterators of values and for
2363/// iterators of references. The product of no numbers is 1 reduced modulo $2^k$, which is 0 when $k
2364/// = 0$.
2365pub trait ModPowerOf2Product<A = Self>: Sized {
2366    fn mod_power_of_2_product<I: Iterator<Item = A>>(xs: I, pow: u64) -> Self;
2367}
2368
2369/// Negates a number modulo $2^k$. The input must be already reduced modulo $2^k$.
2370pub trait ModPowerOf2Neg {
2371    type Output;
2372
2373    fn mod_power_of_2_neg(self, pow: u64) -> Self::Output;
2374}
2375
2376/// Negates a number modulo $2^k$ in place. The input must be already reduced modulo $2^k$.
2377pub trait ModPowerOf2NegAssign {
2378    fn mod_power_of_2_neg_assign(&mut self, pow: u64);
2379}
2380
2381/// Raises a number to a power modulo $2^k$. The base must be already reduced modulo $2^k$.
2382pub trait ModPowerOf2Pow<RHS = Self> {
2383    type Output;
2384
2385    fn mod_power_of_2_pow(self, exp: RHS, pow: u64) -> Self::Output;
2386}
2387
2388/// Raises a number to a power modulo $2^k$, in place. The base must be already reduced modulo
2389/// $2^k$.
2390pub trait ModPowerOf2PowAssign<RHS = Self> {
2391    fn mod_power_of_2_pow_assign(&mut self, exp: RHS, pow: u64);
2392}
2393
2394/// Left-shifts a number (multiplies it by a power of 2) modulo $2^k$. The number must be already
2395/// reduced modulo $2^k$.
2396pub trait ModPowerOf2Shl<RHS> {
2397    type Output;
2398
2399    fn mod_power_of_2_shl(self, other: RHS, pow: u64) -> Self::Output;
2400}
2401
2402/// Left-shifts a number (multiplies it by a power of 2) modulo $2^k$, in place. The number must be
2403/// already reduced modulo $2^k$.
2404pub trait ModPowerOf2ShlAssign<RHS> {
2405    fn mod_power_of_2_shl_assign(&mut self, other: RHS, pow: u64);
2406}
2407
2408/// Right-shifts a number (divides it by a power of 2) modulo $2^k$. The number must be already
2409/// reduced modulo $2^k$.
2410pub trait ModPowerOf2Shr<RHS> {
2411    type Output;
2412
2413    fn mod_power_of_2_shr(self, other: RHS, pow: u64) -> Self::Output;
2414}
2415
2416/// Right-shifts a number (divides it by a power of 2) modulo $2^k$, in place. The number must be
2417/// already reduced modulo $2^k$.
2418pub trait ModPowerOf2ShrAssign<RHS> {
2419    fn mod_power_of_2_shr_assign(&mut self, other: RHS, pow: u64);
2420}
2421
2422/// Squares a number modulo $2^k$. The input must be already reduced modulo $2^k$.
2423pub trait ModPowerOf2Square {
2424    type Output;
2425
2426    fn mod_power_of_2_square(self, pow: u64) -> Self::Output;
2427}
2428
2429/// Squares a number modulo $2^k$ in place. The input must be already reduced modulo $2^k$.
2430pub trait ModPowerOf2SquareAssign {
2431    fn mod_power_of_2_square_assign(&mut self, pow: u64);
2432}
2433
2434/// Computes the squared absolute value of a number modulo $2^k$. The input must be already reduced
2435/// modulo $2^k$.
2436///
2437/// For a real number this is its square modulo $2^k$; the trait exists for the types where it is
2438/// not, such as complex numbers and vectors, for which it is the reduced sum of squares.
2439pub trait ModPowerOf2AbsSquared {
2440    type Output;
2441
2442    fn mod_power_of_2_abs_squared(self, pow: u64) -> Self::Output;
2443}
2444
2445/// Replaces a number with its squared absolute value modulo $2^k$. The input must be already
2446/// reduced modulo $2^k$.
2447pub trait ModPowerOf2AbsSquaredAssign {
2448    fn mod_power_of_2_abs_squared_assign(&mut self, pow: u64);
2449}
2450
2451/// Subtracts two numbers modulo $2^k$. The inputs must be already reduced modulo $2^k$.
2452pub trait ModPowerOf2Sub<RHS = Self> {
2453    type Output;
2454
2455    fn mod_power_of_2_sub(self, other: RHS, pow: u64) -> Self::Output;
2456}
2457
2458/// Subtracts two numbers modulo $2^k$, in place. The inputs must be already reduced modulo $2^k$.
2459pub trait ModPowerOf2SubAssign<RHS = Self> {
2460    fn mod_power_of_2_sub_assign(&mut self, other: RHS, pow: u64);
2461}
2462
2463/// Divides a number by $2^k$, returning the balanced remainder: the representative of the number
2464/// modulo $2^k$ that is closest to zero.
2465///
2466/// The remainder $r$ satisfies $-2^{k-1} < r \leq 2^{k-1}$, so a remainder of exactly $2^{k-1}$ is
2467/// positive, as with [`BalancedMod`]; for $k = 0$ it is 0. It is congruent to $x$ modulo $2^k$, and
2468/// those two properties determine it uniquely.
2469pub trait BalancedModPowerOf2 {
2470    type Output;
2471
2472    fn balanced_mod_power_of_2(self, pow: u64) -> Self::Output;
2473}
2474
2475/// Divides a number by $2^k$, replacing the number by the balanced remainder: the representative of
2476/// the number modulo $2^k$ that is closest to zero.
2477///
2478/// The remainder $r$ satisfies $-2^{k-1} < r \leq 2^{k-1}$, so a remainder of exactly $2^{k-1}$ is
2479/// positive; for $k = 0$ it is 0.
2480pub trait BalancedModPowerOf2Assign {
2481    fn balanced_mod_power_of_2_assign(&mut self, pow: u64);
2482}
2483
2484/// Divides a number by $2^k$, returning just the remainder. The remainder is non-negative.
2485///
2486/// If the quotient were computed, the quotient and remainder would satisfy $x = q2^k + r$ and $0
2487/// \leq r < 2^k$.
2488pub trait ModPowerOf2 {
2489    type Output;
2490
2491    fn mod_power_of_2(self, other: u64) -> Self::Output;
2492}
2493
2494/// Divides a number by $2^k$, replacing the number by the remainder. The remainder is non-negative.
2495///
2496/// If the quotient were computed, the quotient and remainder would satisfy $x = q2^k + r$ and $0
2497/// \leq r < 2^k$.
2498pub trait ModPowerOf2Assign {
2499    fn mod_power_of_2_assign(&mut self, other: u64);
2500}
2501
2502/// Divides a number by $2^k$, returning just the remainder. The remainder has the same sign as the
2503/// number.
2504///
2505/// If the quotient were computed, the quotient and remainder would satisfy $x = q2^k + r$ and $0
2506/// \leq |r| < 2^k$.
2507pub trait RemPowerOf2 {
2508    type Output;
2509
2510    fn rem_power_of_2(self, other: u64) -> Self::Output;
2511}
2512
2513/// Divides a number by $2^k$, replacing the number by the remainder. The remainder has the same
2514/// sign as the number.
2515///
2516/// If the quotient were computed, the quotient and remainder would satisfy $x = q2^k + r$ and $0
2517/// \leq |r| < 2^k$.
2518pub trait RemPowerOf2Assign {
2519    fn rem_power_of_2_assign(&mut self, other: u64);
2520}
2521
2522/// Divides the negative of a number by $2^k$, returning the remainder.
2523///
2524/// If the quotient were computed, the quotient and remainder would satisfy $x = q2^k - r$ and $0
2525/// \leq r < 2^k$.
2526pub trait NegModPowerOf2 {
2527    type Output;
2528
2529    fn neg_mod_power_of_2(self, other: u64) -> Self::Output;
2530}
2531
2532/// Divides the negative of a number by $2^k$, replacing the number by the remainder.
2533///
2534/// If the quotient were computed, the quotient and remainder would satisfy $x = q2^k - r$ and $0
2535/// \leq r < 2^k$.
2536pub trait NegModPowerOf2Assign {
2537    fn neg_mod_power_of_2_assign(&mut self, other: u64);
2538}
2539
2540/// Divides a number by $2^k$, returning just the remainder. The remainder is non-positive.
2541///
2542/// If the quotient were computed, the quotient and remainder would satisfy $x = q2^k + r$ and $0
2543/// \leq -r < 2^k$.
2544pub trait CeilingModPowerOf2 {
2545    type Output;
2546
2547    fn ceiling_mod_power_of_2(self, other: u64) -> Self::Output;
2548}
2549
2550/// Divides a number by $2^k$, replacing the number by the remainder. The remainder is non-positive.
2551///
2552/// If the quotient were computed, the quotient and remainder would satisfy $x = q2^k + r$ and $0
2553/// \leq -r < 2^k$.
2554pub trait CeilingModPowerOf2Assign {
2555    fn ceiling_mod_power_of_2_assign(&mut self, other: u64);
2556}
2557
2558/// Left-shifts a number (multiplies it by a power of 2) modulo another number $m$. The number must
2559/// be already reduced modulo $m$.
2560pub trait ModShl<RHS, M = Self> {
2561    type Output;
2562
2563    fn mod_shl(self, other: RHS, m: M) -> Self::Output;
2564}
2565
2566/// Left-shifts a number (multiplies it by a power of 2) modulo another number $m$, in place. The
2567/// number must be already reduced modulo $m$.
2568pub trait ModShlAssign<RHS, M = Self> {
2569    fn mod_shl_assign(&mut self, other: RHS, m: M);
2570}
2571
2572/// Right-shifts a number (divides it by a power of 2) modulo another number $m$. The number must be
2573/// already reduced modulo $m$.
2574pub trait ModShr<RHS, M = Self> {
2575    type Output;
2576
2577    fn mod_shr(self, other: RHS, m: M) -> Self::Output;
2578}
2579
2580/// Right-shifts a number (divides it by a power of 2) modulo another number $m$, in place. The
2581/// number must be already reduced modulo $m$.
2582pub trait ModShrAssign<RHS, M = Self> {
2583    fn mod_shr_assign(&mut self, other: RHS, m: M);
2584}
2585
2586/// Computes a square root of a number modulo another number $m$, returning `None` if no root is
2587/// found. The input must be already reduced modulo $m$.
2588///
2589/// The modulus should be an odd prime: for such moduli a root is found whenever one exists. The
2590/// behavior for other moduli is deterministic and never hangs, but a root may be missed, and a
2591/// returned value may fail to be a root.
2592pub trait ModSqrt<M = Self> {
2593    type Output;
2594
2595    fn mod_sqrt(self, m: M) -> Option<Self::Output>;
2596}
2597
2598/// Squares a number modulo another number $m$. The input must be already reduced modulo $m$.
2599pub trait ModSquare<M = Self> {
2600    type Output;
2601
2602    fn mod_square(self, m: M) -> Self::Output;
2603}
2604
2605/// Squares a number modulo another number $m$, in place. The input must be already reduced modulo
2606/// $m$.
2607pub trait ModSquareAssign<M = Self> {
2608    fn mod_square_assign(&mut self, m: M);
2609}
2610
2611/// Computes the squared absolute value of a number modulo another number $m$. The input must be
2612/// already reduced modulo $m$.
2613///
2614/// For a real number this is its square modulo $m$; the trait exists for the types where it is not,
2615/// such as complex numbers and vectors, for which it is the reduced sum of squares.
2616pub trait ModAbsSquared<M = Self> {
2617    type Output;
2618
2619    fn mod_abs_squared(self, m: M) -> Self::Output;
2620}
2621
2622/// Replaces a number with its squared absolute value modulo another number $m$. The input must be
2623/// already reduced modulo $m$.
2624pub trait ModAbsSquaredAssign<M = Self> {
2625    fn mod_abs_squared_assign(&mut self, m: M);
2626}
2627
2628/// Squares a number modulo another number $m$. The input must be already reduced modulo $m$.
2629///
2630/// If multiple modular squarings with the same modulus are necessary, it can be quicker to
2631/// precompute some piece of data using
2632/// [`precompute_mod_pow_data`](ModPowPrecomputed::precompute_mod_pow_data) function in
2633/// [`ModMulPrecomputed`] and reuse it in the squaring calls.
2634pub trait ModSquarePrecomputed<RHS = Self, M = Self>: ModPowPrecomputed<RHS, M>
2635where
2636    Self: Sized,
2637{
2638    fn mod_square_precomputed(self, m: M, data: &Self::Data) -> Self::Output;
2639}
2640
2641/// Squares a number modulo another number $m$, in place. The input must be already reduced modulo
2642/// $m$.
2643///
2644/// If multiple modular squarings with the same modulus are necessary, it can be quicker to
2645/// precompute some piece of data using
2646/// [`precompute_mod_pow_data`](ModPowPrecomputed::precompute_mod_pow_data) function in
2647/// [`ModMulPrecomputed`] and reuse it in the squaring calls.
2648pub trait ModSquarePrecomputedAssign<RHS = Self, M = Self>: ModPowPrecomputed<RHS, M> {
2649    fn mod_square_precomputed_assign(&mut self, m: M, data: &Self::Data);
2650}
2651
2652/// Adds two numbers modulo a third number $m$. The inputs must be already reduced modulo $m$.
2653pub trait ModSub<RHS = Self, M = Self> {
2654    type Output;
2655
2656    fn mod_sub(self, other: RHS, m: M) -> Self::Output;
2657}
2658
2659/// Adds two numbers modulo a third number $m$, in place. The inputs must be already reduced modulo
2660/// $m$.
2661pub trait ModSubAssign<RHS = Self, M = Self> {
2662    fn mod_sub_assign(&mut self, other: RHS, m: M);
2663}
2664
2665/// Replaces a number with its negative. Assumes the result is representable.
2666pub trait NegAssign {
2667    fn neg_assign(&mut self);
2668}
2669
2670/// Returns the smallest power of 2 greater than or equal to a number. Assumes the result is
2671/// representable.
2672pub trait NextPowerOf2 {
2673    type Output;
2674
2675    fn next_power_of_2(self) -> Self::Output;
2676}
2677
2678/// Replaces a number with the smallest power of 2 greater than or equal it. Assumes the result is
2679/// representable.
2680pub trait NextPowerOf2Assign {
2681    fn next_power_of_2_assign(&mut self);
2682}
2683
2684/// Takes the absolute value of a number.
2685///
2686/// Returns a tuple of the result along with a boolean indicating whether an arithmetic overflow
2687/// occurred. If an overflow occurred, then the wrapped number is returned.
2688pub trait OverflowingAbs {
2689    type Output;
2690
2691    fn overflowing_abs(self) -> (Self::Output, bool);
2692}
2693
2694/// Replaces a number with its absolute value.
2695///
2696/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2697/// then the wrapped number is assigned.
2698pub trait OverflowingAbsAssign {
2699    fn overflowing_abs_assign(&mut self) -> bool;
2700}
2701
2702/// Adds two numbers.
2703///
2704/// Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow
2705/// occurred. If an overflow occurred, then the wrapped number is returned.
2706pub trait OverflowingAdd<RHS = Self> {
2707    type Output;
2708
2709    fn overflowing_add(self, other: RHS) -> (Self::Output, bool);
2710}
2711
2712/// Adds a number to another number in place.
2713///
2714/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2715/// then the wrapped number is assigned.
2716pub trait OverflowingAddAssign<RHS = Self> {
2717    fn overflowing_add_assign(&mut self, other: RHS) -> bool;
2718}
2719
2720/// Adds a number and the product of two other numbers.
2721///
2722/// Returns a tuple of the result along with a boolean indicating whether an arithmetic overflow
2723/// occurred. If an overflow occurred, then the wrapped number is returned.
2724pub trait OverflowingAddMul<Y = Self, Z = Self> {
2725    type Output;
2726
2727    fn overflowing_add_mul(self, y: Y, z: Z) -> (Self::Output, bool);
2728}
2729
2730/// Adds a number and the product of two other numbers, in place.
2731///
2732/// Returns a tuple of the result along with a boolean indicating whether an arithmetic overflow
2733/// occurred. If an overflow occurred, then the wrapped number is returned.
2734pub trait OverflowingAddMulAssign<Y = Self, Z = Self> {
2735    fn overflowing_add_mul_assign(&mut self, y: Y, z: Z) -> bool;
2736}
2737
2738/// Adds the products of two pairs of numbers.
2739///
2740/// Returns a tuple of the result along with a boolean indicating whether an arithmetic overflow
2741/// occurred. If an overflow occurred, then the wrapped result is returned.
2742pub trait OverflowingMulAddMul<Y = Self, Z = Self, W = Self> {
2743    type Output;
2744
2745    fn overflowing_mul_add_mul(self, y: Y, z: Z, w: W) -> (Self::Output, bool);
2746}
2747
2748/// Adds the products of two pairs of numbers, in place.
2749///
2750/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2751/// then the wrapped result is assigned.
2752pub trait OverflowingMulAddMulAssign<Y = Self, Z = Self, W = Self> {
2753    fn overflowing_mul_add_mul_assign(&mut self, y: Y, z: Z, w: W) -> bool;
2754}
2755
2756/// Subtracts the product of one pair of numbers from the product of another.
2757///
2758/// Returns a tuple of the result along with a boolean indicating whether an arithmetic overflow
2759/// occurred. If an overflow occurred, then the wrapped result is returned.
2760pub trait OverflowingMulSubMul<Y = Self, Z = Self, W = Self> {
2761    type Output;
2762
2763    fn overflowing_mul_sub_mul(self, y: Y, z: Z, w: W) -> (Self::Output, bool);
2764}
2765
2766/// Subtracts the product of one pair of numbers from the product of another, in place.
2767///
2768/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2769/// then the wrapped result is assigned.
2770pub trait OverflowingMulSubMulAssign<Y = Self, Z = Self, W = Self> {
2771    fn overflowing_mul_sub_mul_assign(&mut self, y: Y, z: Z, w: W) -> bool;
2772}
2773
2774/// Divides two numbers.
2775///
2776/// Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow
2777/// occurred. If an overflow occurred, then the wrapped number is returned.
2778pub trait OverflowingDiv<RHS = Self> {
2779    type Output;
2780
2781    fn overflowing_div(self, other: RHS) -> (Self::Output, bool);
2782}
2783
2784/// Divides a number by another number in place.
2785///
2786/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2787/// then the wrapped number is assigned.
2788pub trait OverflowingDivAssign<RHS = Self> {
2789    fn overflowing_div_assign(&mut self, other: RHS) -> bool;
2790}
2791
2792/// Multiplies two numbers.
2793///
2794/// Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow
2795/// occurred. If an overflow occurred, then the wrapped number is returned.
2796pub trait OverflowingMul<RHS = Self> {
2797    type Output;
2798
2799    fn overflowing_mul(self, other: RHS) -> (Self::Output, bool);
2800}
2801
2802/// Multiplies a number by another number in place.
2803///
2804/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2805/// then the wrapped number is assigned.
2806pub trait OverflowingMulAssign<RHS = Self> {
2807    fn overflowing_mul_assign(&mut self, other: RHS) -> bool;
2808}
2809
2810/// Negates a number.
2811///
2812/// Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow
2813/// occurred. If an overflow occurred, then the wrapped number is returned.
2814pub trait OverflowingNeg {
2815    type Output;
2816
2817    fn overflowing_neg(self) -> (Self::Output, bool);
2818}
2819
2820/// Negates a number in place.
2821///
2822/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2823/// then the wrapped number is assigned.
2824pub trait OverflowingNegAssign {
2825    fn overflowing_neg_assign(&mut self) -> bool;
2826}
2827
2828/// Raises a number to a power.
2829///
2830/// Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow
2831/// occurred. If an overflow occurred, then the wrapped number is returned.
2832pub trait OverflowingPow<RHS> {
2833    type Output;
2834
2835    fn overflowing_pow(self, exp: RHS) -> (Self::Output, bool);
2836}
2837
2838/// Raises a number to a power in place.
2839///
2840/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2841/// then the wrapped number is assigned.
2842pub trait OverflowingPowAssign<RHS = Self> {
2843    fn overflowing_pow_assign(&mut self, exp: RHS) -> bool;
2844}
2845
2846/// Squares a number.
2847///
2848/// Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow
2849/// occurred. If an overflow occurred, then the wrapped number is returned.
2850pub trait OverflowingSquare {
2851    type Output;
2852
2853    fn overflowing_square(self) -> (Self::Output, bool);
2854}
2855
2856/// Squares a number in place.
2857///
2858/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2859/// then the wrapped number is assigned.
2860pub trait OverflowingSquareAssign {
2861    fn overflowing_square_assign(&mut self) -> bool;
2862}
2863
2864/// Subtracts two numbers.
2865///
2866/// Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow
2867/// occurred. If an overflow occurred, then the wrapped number is returned.
2868pub trait OverflowingSub<RHS = Self> {
2869    type Output;
2870
2871    fn overflowing_sub(self, other: RHS) -> (Self::Output, bool);
2872}
2873
2874/// Subtracts a number by another number in place.
2875///
2876/// Returns a boolean indicating whether an arithmetic overflow occurred. If an overflow occurred,
2877/// then the wrapped number is assigned.
2878pub trait OverflowingSubAssign<RHS = Self> {
2879    fn overflowing_sub_assign(&mut self, other: RHS) -> bool;
2880}
2881
2882/// Subtracts a number by the product of two other numbers.
2883///
2884/// Returns a tuple of the result along with a boolean indicating whether an arithmetic overflow
2885/// occurred. If an overflow occurred, then the wrapped number is returned.
2886pub trait OverflowingSubMul<Y = Self, Z = Self> {
2887    type Output;
2888
2889    fn overflowing_sub_mul(self, y: Y, z: Z) -> (Self::Output, bool);
2890}
2891
2892/// Subtracts a number by the product of two other numbers, in place.
2893///
2894/// Returns a tuple of the result along with a boolean indicating whether an arithmetic overflow
2895/// occurred. If an overflow occurred, then the wrapped number is returned.
2896pub trait OverflowingSubMulAssign<Y = Self, Z = Self> {
2897    fn overflowing_sub_mul_assign(&mut self, y: Y, z: Z) -> bool;
2898}
2899
2900/// Determines whether a number is even or odd.
2901pub trait Parity {
2902    /// Determines whether a number is even.
2903    fn even(self) -> bool;
2904
2905    /// Determines whether a number is odd.
2906    fn odd(self) -> bool;
2907}
2908
2909/// Raises a number to a power. Assumes the result is representable.
2910pub trait Pow<RHS> {
2911    type Output;
2912
2913    fn pow(self, exp: RHS) -> Self::Output;
2914}
2915
2916/// Raises a number to a power in place. Assumes the result is representable.
2917pub trait PowAssign<RHS = Self> {
2918    fn pow_assign(&mut self, exp: RHS);
2919}
2920
2921/// Raises 2 to a power.
2922pub trait PowerOf2<POW> {
2923    fn power_of_2(pow: POW) -> Self;
2924}
2925
2926/// Replaces a number with 2 raised to the power of that number.
2927pub trait PowerOf2Assign {
2928    fn power_of_2_assign(&mut self);
2929}
2930
2931/// Raises 10 to a power.
2932pub trait PowerOf10<POW> {
2933    fn power_of_10(pow: POW) -> Self;
2934}
2935
2936/// Replaces a number with 10 raised to the power of that number.
2937pub trait PowerOf10Assign {
2938    fn power_of_10_assign(&mut self);
2939}
2940
2941pub trait Primorial {
2942    fn primorial(n: u64) -> Self;
2943
2944    fn product_of_first_n_primes(n: u64) -> Self;
2945}
2946
2947pub trait CheckedPrimorial: Sized {
2948    fn checked_primorial(n: u64) -> Option<Self>;
2949
2950    fn checked_product_of_first_n_primes(n: u64) -> Option<Self>;
2951}
2952
2953/// Finds the reciprocal (multiplicative inverse) of a number.
2954pub trait Reciprocal {
2955    type Output;
2956
2957    fn reciprocal(self) -> Self::Output;
2958}
2959
2960/// Replaces a number with its reciprocal (multiplicative inverse).
2961pub trait ReciprocalAssign {
2962    fn reciprocal_assign(&mut self);
2963}
2964
2965/// Takes the reciprocal of the square root of a number.
2966pub trait ReciprocalSqrt {
2967    type Output;
2968
2969    fn reciprocal_sqrt(self) -> Self::Output;
2970}
2971
2972/// Replaces a number with the reciprocal of its square root.
2973pub trait ReciprocalSqrtAssign {
2974    fn reciprocal_sqrt_assign(&mut self);
2975}
2976
2977/// Finds the floor of the $n$th root of a number.
2978pub trait FloorRoot<POW> {
2979    type Output;
2980
2981    fn floor_root(self, pow: POW) -> Self::Output;
2982}
2983
2984/// Replaces a number with the floor of its $n$th root.
2985pub trait FloorRootAssign<POW> {
2986    fn floor_root_assign(&mut self, pow: POW);
2987}
2988
2989/// Finds the ceiling of the $n$th root of a number.
2990pub trait CeilingRoot<POW> {
2991    type Output;
2992
2993    fn ceiling_root(self, pow: POW) -> Self::Output;
2994}
2995
2996/// Replaces a number with the ceiling of its $n$th root.
2997pub trait CeilingRootAssign<POW> {
2998    fn ceiling_root_assign(&mut self, pow: POW);
2999}
3000
3001/// Finds the $n$th root of a number, returning `None` if it is not a perfect $n$th power.
3002pub trait CheckedRoot<POW> {
3003    type Output;
3004
3005    fn checked_root(self, pow: POW) -> Option<Self::Output>;
3006}
3007
3008/// Finds the floor of the $n$th root of a number, returning both the root and the remainder.
3009pub trait RootRem<POW> {
3010    type RootOutput;
3011    type RemOutput;
3012
3013    fn root_rem(self, exp: POW) -> (Self::RootOutput, Self::RemOutput);
3014}
3015
3016/// Replaces a number with the floor of its $n$th root, returning the remainder.
3017pub trait RootAssignRem<POW> {
3018    type RemOutput;
3019
3020    fn root_assign_rem(&mut self, exp: POW) -> Self::RemOutput;
3021}
3022
3023/// Takes the $n$th root of a number.
3024pub trait Root<POW> {
3025    type Output;
3026
3027    fn root(self, pow: POW) -> Self::Output;
3028}
3029
3030/// Replaces a number with its $n$th root.
3031pub trait RootAssign<POW> {
3032    fn root_assign(&mut self, pow: POW);
3033}
3034
3035/// Takes the cube root of a number.
3036pub trait Cbrt {
3037    type Output;
3038
3039    fn cbrt(self) -> Self::Output;
3040}
3041
3042/// Replaces a number with its cube root.
3043pub trait CbrtAssign {
3044    fn cbrt_assign(&mut self);
3045}
3046
3047/// Rotates a number left, inserting the leftmost bits into the right end.
3048pub trait RotateLeft {
3049    type Output;
3050
3051    fn rotate_left(self, n: u64) -> Self::Output;
3052}
3053
3054/// Rotates a number left, inserting the leftmost bits into the right end, in place.
3055pub trait RotateLeftAssign {
3056    fn rotate_left_assign(&mut self, n: u64);
3057}
3058
3059/// Rotates a number right, inserting the leftmost bits into the left end.
3060pub trait RotateRight {
3061    type Output;
3062
3063    fn rotate_right(self, n: u64) -> Self::Output;
3064}
3065
3066/// Rotates a number right, inserting the leftmost bits into the left end, in place.
3067pub trait RotateRightAssign {
3068    fn rotate_right_assign(&mut self, n: u64);
3069}
3070
3071/// Rounds a number to a multiple of another number, according to a specified rounding mode. An
3072/// [`Ordering`] is also returned, indicating whether the returned value is less than, equal to, or
3073/// greater than the original value.
3074pub trait RoundToMultiple<RHS = Self> {
3075    type Output;
3076
3077    fn round_to_multiple(self, other: RHS, rm: RoundingMode) -> (Self::Output, Ordering);
3078}
3079
3080/// Rounds a number to a multiple of another number in place, according to a specified rounding
3081/// mode. [`Ordering`] is returned, indicating whether the returned value is less than, equal to, or
3082/// greater than the original value.
3083pub trait RoundToMultipleAssign<RHS = Self> {
3084    fn round_to_multiple_assign(&mut self, other: RHS, rm: RoundingMode) -> Ordering;
3085}
3086
3087/// Rounds a number to a multiple of $2^k$, according to a specified rounding mode. An [`Ordering`]
3088/// is also returned, indicating whether the returned value is less than, equal to, or greater than
3089/// the original value.
3090pub trait RoundToMultipleOfPowerOf2<RHS> {
3091    type Output;
3092
3093    fn round_to_multiple_of_power_of_2(
3094        self,
3095        pow: RHS,
3096        rm: RoundingMode,
3097    ) -> (Self::Output, Ordering);
3098}
3099
3100/// Rounds a number to a multiple of $2^k$ in place, according to a specified rounding mode. An
3101/// [`Ordering`] is returned, indicating whether the returned value is less than, equal to, or
3102/// greater than the original value.
3103pub trait RoundToMultipleOfPowerOf2Assign<RHS> {
3104    fn round_to_multiple_of_power_of_2_assign(&mut self, pow: RHS, rm: RoundingMode) -> Ordering;
3105}
3106
3107/// Takes the absolute value of a number, saturating at the numeric bounds instead of overflowing.
3108pub trait SaturatingAbs {
3109    type Output;
3110
3111    fn saturating_abs(self) -> Self::Output;
3112}
3113
3114/// Replaces a number with its absolute value, saturating at the numeric bounds instead of
3115/// overflowing.
3116pub trait SaturatingAbsAssign {
3117    fn saturating_abs_assign(&mut self);
3118}
3119
3120/// Adds two numbers, saturating at the numeric bounds instead of overflowing.
3121pub trait SaturatingAdd<RHS = Self> {
3122    type Output;
3123
3124    fn saturating_add(self, other: RHS) -> Self::Output;
3125}
3126
3127/// Add a number to another number in place, saturating at the numeric bounds instead of
3128/// overflowing.
3129pub trait SaturatingAddAssign<RHS = Self> {
3130    fn saturating_add_assign(&mut self, other: RHS);
3131}
3132
3133/// Adds a number and the product of two other numbers, saturating at the numeric bounds instead of
3134/// overflowing.
3135pub trait SaturatingAddMul<Y = Self, Z = Self> {
3136    type Output;
3137
3138    fn saturating_add_mul(self, y: Y, z: Z) -> Self::Output;
3139}
3140
3141/// Adds a number and the product of two other numbers in place, saturating at the numeric bounds
3142/// instead of overflowing.
3143pub trait SaturatingAddMulAssign<Y = Self, Z = Self> {
3144    fn saturating_add_mul_assign(&mut self, y: Y, z: Z);
3145}
3146
3147/// Adds the products of two pairs of numbers, saturating at the numeric bounds instead of
3148/// overflowing.
3149pub trait SaturatingMulAddMul<Y = Self, Z = Self, W = Self> {
3150    type Output;
3151
3152    fn saturating_mul_add_mul(self, y: Y, z: Z, w: W) -> Self::Output;
3153}
3154
3155/// Adds the products of two pairs of numbers, in place, saturating at the numeric bounds instead of
3156/// overflowing.
3157pub trait SaturatingMulAddMulAssign<Y = Self, Z = Self, W = Self> {
3158    fn saturating_mul_add_mul_assign(&mut self, y: Y, z: Z, w: W);
3159}
3160
3161/// Subtracts the product of one pair of numbers from the product of another, saturating at the
3162/// numeric bounds instead of overflowing.
3163pub trait SaturatingMulSubMul<Y = Self, Z = Self, W = Self> {
3164    type Output;
3165
3166    fn saturating_mul_sub_mul(self, y: Y, z: Z, w: W) -> Self::Output;
3167}
3168
3169/// Subtracts the product of one pair of numbers from the product of another, in place, saturating
3170/// at the numeric bounds instead of overflowing.
3171pub trait SaturatingMulSubMulAssign<Y = Self, Z = Self, W = Self> {
3172    fn saturating_mul_sub_mul_assign(&mut self, y: Y, z: Z, w: W);
3173}
3174
3175/// Multiplies two numbers, saturating at the numeric bounds instead of overflowing.
3176pub trait SaturatingMul<RHS = Self> {
3177    type Output;
3178
3179    fn saturating_mul(self, other: RHS) -> Self::Output;
3180}
3181
3182/// Multiplies a number by another number in place, saturating at the numeric bounds instead of
3183/// overflowing.
3184pub trait SaturatingMulAssign<RHS = Self> {
3185    fn saturating_mul_assign(&mut self, other: RHS);
3186}
3187
3188/// Negates a number, saturating at the numeric bounds instead of overflowing.
3189pub trait SaturatingNeg {
3190    type Output;
3191
3192    fn saturating_neg(self) -> Self::Output;
3193}
3194
3195/// Negates a number in place, saturating at the numeric bounds instead of overflowing.
3196pub trait SaturatingNegAssign {
3197    fn saturating_neg_assign(&mut self);
3198}
3199
3200/// Raises a number to a power, saturating at the numeric bounds instead of overflowing.
3201pub trait SaturatingPow<RHS> {
3202    type Output;
3203
3204    fn saturating_pow(self, exp: RHS) -> Self::Output;
3205}
3206
3207/// Raises a number to a power in place, saturating at the numeric bounds instead of overflowing.
3208pub trait SaturatingPowAssign<RHS = Self> {
3209    fn saturating_pow_assign(&mut self, exp: RHS);
3210}
3211
3212/// Squares a number, saturating at the numeric bounds instead of overflowing.
3213pub trait SaturatingSquare {
3214    type Output;
3215
3216    fn saturating_square(self) -> Self::Output;
3217}
3218
3219/// Squares a number in place, saturating at the numeric bounds instead of overflowing.
3220pub trait SaturatingSquareAssign {
3221    fn saturating_square_assign(&mut self);
3222}
3223
3224/// Subtracts two numbers, saturating at the numeric bounds instead of overflowing.
3225pub trait SaturatingSub<RHS = Self> {
3226    type Output;
3227
3228    fn saturating_sub(self, other: RHS) -> Self::Output;
3229}
3230
3231/// Subtracts a number by another number in place, saturating at the numeric bounds instead of
3232/// overflowing.
3233pub trait SaturatingSubAssign<RHS = Self> {
3234    fn saturating_sub_assign(&mut self, other: RHS);
3235}
3236
3237/// Subtracts a number by the product of two other numbers, saturating at the numeric bounds instead
3238/// of overflowing.
3239pub trait SaturatingSubMul<Y = Self, Z = Self> {
3240    type Output;
3241
3242    fn saturating_sub_mul(self, y: Y, z: Z) -> Self::Output;
3243}
3244
3245/// Subtracts a number by the product of two other numbers in place, saturating at the numeric
3246/// bounds instead of overflowing.
3247pub trait SaturatingSubMulAssign<Y = Self, Z = Self> {
3248    fn saturating_sub_mul_assign(&mut self, y: Y, z: Z);
3249}
3250
3251/// Left-shifts a number (multiplies it by a power of 2), rounding the result according to a
3252/// specified rounding mode. An [`Ordering`] is also returned, indicating whether the returned value
3253/// is less than, equal to, or greater than the exact value.
3254///
3255/// Rounding might only be necessary if `other` is negative.
3256pub trait ShlRound<RHS> {
3257    type Output;
3258
3259    fn shl_round(self, other: RHS, rm: RoundingMode) -> (Self::Output, Ordering);
3260}
3261
3262/// Left-shifts a number (multiplies it by a power of 2) in place, rounding the result according to
3263/// a specified rounding mode. An [`Ordering`] is also returned, indicating whether the assigned
3264/// value is less than, equal to, or greater than the exact value.
3265///
3266/// Rounding might only be necessary if `other` is negative.
3267pub trait ShlRoundAssign<RHS> {
3268    fn shl_round_assign(&mut self, other: RHS, rm: RoundingMode) -> Ordering;
3269}
3270
3271/// Right-shifts a number (divides it by a power of 2), rounding the result according to a specified
3272/// rounding mode. An [`Ordering`] is also returned, indicating whether the returned value is less
3273/// than, equal to, or greater than the exact value.
3274///
3275/// Rounding might only be necessary if `other` is positive.
3276pub trait ShrRound<RHS> {
3277    type Output;
3278
3279    fn shr_round(self, other: RHS, rm: RoundingMode) -> (Self::Output, Ordering);
3280}
3281
3282/// Right-shifts a number (divides it by a power of 2) in place, rounding the result according to a
3283/// specified rounding mode. An [`Ordering`] is also returned, indicating whether the assigned value
3284/// is less than, equal to, or greater than the exact value.
3285///
3286/// Rounding might only be necessary if `other` is positive.
3287pub trait ShrRoundAssign<RHS> {
3288    fn shr_round_assign(&mut self, other: RHS, rm: RoundingMode) -> Ordering;
3289}
3290
3291/// Returns `Greater`, `Equal`, or `Less`, depending on whether a number is positive, zero, or
3292/// negative, respectively.
3293pub trait Sign {
3294    fn sign(&self) -> Ordering;
3295}
3296
3297/// Takes the square root of a number.
3298pub trait Sqrt {
3299    type Output;
3300
3301    fn sqrt(self) -> Self::Output;
3302}
3303
3304/// Replaces a number with its square root.
3305pub trait SqrtAssign {
3306    fn sqrt_assign(&mut self);
3307}
3308
3309/// Finds the floor of the square root of a number.
3310pub trait FloorSqrt {
3311    type Output;
3312
3313    fn floor_sqrt(self) -> Self::Output;
3314}
3315
3316/// Replaces a number with the floor of its square root.
3317pub trait FloorSqrtAssign {
3318    fn floor_sqrt_assign(&mut self);
3319}
3320
3321/// Finds the ceiling of the square root of a number.
3322pub trait CeilingSqrt {
3323    type Output;
3324
3325    fn ceiling_sqrt(self) -> Self::Output;
3326}
3327
3328/// Replaces a number with the ceiling of its square root.
3329pub trait CeilingSqrtAssign {
3330    fn ceiling_sqrt_assign(&mut self);
3331}
3332
3333/// Finds the square root of a number, returning `None` if it is not a perfect square.
3334pub trait CheckedSqrt {
3335    type Output;
3336
3337    fn checked_sqrt(self) -> Option<Self::Output>;
3338}
3339
3340/// Finds the floor of the square root of a number, returning both the root and the remainder.
3341pub trait SqrtRem {
3342    type SqrtOutput;
3343    type RemOutput;
3344
3345    fn sqrt_rem(self) -> (Self::SqrtOutput, Self::RemOutput);
3346}
3347
3348/// Replaces a number with the floor of its square root, returning the remainder.
3349pub trait SqrtAssignRem {
3350    type RemOutput;
3351
3352    fn sqrt_assign_rem(&mut self) -> Self::RemOutput;
3353}
3354
3355/// Squares a number.
3356pub trait Square {
3357    type Output;
3358
3359    fn square(self) -> Self::Output;
3360}
3361
3362/// Replaces a number with its square.
3363pub trait SquareAssign {
3364    fn square_assign(&mut self);
3365}
3366
3367/// Subtracts a number by the product of two other numbers.
3368///
3369/// Depending on the implementing type, the fused operation may compute the same value as the
3370/// unfused `self - y * z` more efficiently; or, for types with rounding, it may compute a *more
3371/// accurate* value -- the product enters the subtraction exactly, with a single rounding at the end
3372/// -- but *less* efficiently, since the exact product must be computed in full. See each
3373/// implementation's documentation for which contract it provides.
3374pub trait SubMul<Y = Self, Z = Self> {
3375    type Output;
3376
3377    fn sub_mul(self, y: Y, z: Z) -> Self::Output;
3378}
3379
3380/// Subtracts a number by the product of two other numbers, in place.
3381///
3382/// Depending on the implementing type, the fused operation may compute the same value as the
3383/// unfused `*self - y * z` more efficiently; or, for types with rounding, it may compute a *more
3384/// accurate* value -- the product enters the subtraction exactly, with a single rounding at the end
3385/// -- but *less* efficiently, since the exact product must be computed in full. See each
3386/// implementation's documentation for which contract it provides.
3387pub trait SubMulAssign<Y = Self, Z = Self> {
3388    fn sub_mul_assign(&mut self, y: Y, z: Z);
3389}
3390
3391/// Subtracts the product of two numbers, shifted left by a number of bits, from a number: $x -
3392/// yz2^k$.
3393pub trait SubMulShl<Y = Self, Z = Self> {
3394    type Output;
3395
3396    fn sub_mul_shl(self, y: Y, z: Z, bits: u64) -> Self::Output;
3397}
3398
3399/// Subtracts the product of two numbers, shifted left by a number of bits, from a number in place:
3400/// $x \gets x - yz2^k$.
3401pub trait SubMulShlAssign<Y = Self, Z = Self> {
3402    fn sub_mul_shl_assign(&mut self, y: Y, z: Z, bits: u64);
3403}
3404
3405/// Takes the absolute value of a number, wrapping around at the boundary of the type.
3406pub trait WrappingAbs {
3407    type Output;
3408
3409    fn wrapping_abs(self) -> Self::Output;
3410}
3411
3412/// Replaces a number with its absolute value, wrapping around at the boundary of the type.
3413pub trait WrappingAbsAssign {
3414    fn wrapping_abs_assign(&mut self);
3415}
3416
3417/// Adds two numbers, wrapping around at the boundary of the type.
3418pub trait WrappingAdd<RHS = Self> {
3419    type Output;
3420
3421    fn wrapping_add(self, other: RHS) -> Self::Output;
3422}
3423
3424/// Adds a number to another number in place, wrapping around at the boundary of the type.
3425pub trait WrappingAddAssign<RHS = Self> {
3426    fn wrapping_add_assign(&mut self, other: RHS);
3427}
3428
3429/// Adds a number and the product of two other numbers, wrapping around at the boundary of the type.
3430pub trait WrappingAddMul<Y = Self, Z = Self> {
3431    type Output;
3432
3433    fn wrapping_add_mul(self, y: Y, z: Z) -> Self::Output;
3434}
3435
3436/// Adds a number and the product of two other numbers, in place, wrapping around at the boundary of
3437/// the type.
3438pub trait WrappingAddMulAssign<Y = Self, Z = Self> {
3439    fn wrapping_add_mul_assign(&mut self, y: Y, z: Z);
3440}
3441
3442/// Adds the products of two pairs of numbers, wrapping around at the boundary of the type.
3443pub trait WrappingMulAddMul<Y = Self, Z = Self, W = Self> {
3444    type Output;
3445
3446    fn wrapping_mul_add_mul(self, y: Y, z: Z, w: W) -> Self::Output;
3447}
3448
3449/// Adds the products of two pairs of numbers, in place, wrapping around at the boundary of the
3450/// type.
3451pub trait WrappingMulAddMulAssign<Y = Self, Z = Self, W = Self> {
3452    fn wrapping_mul_add_mul_assign(&mut self, y: Y, z: Z, w: W);
3453}
3454
3455/// Subtracts the product of one pair of numbers from the product of another, wrapping around at the
3456/// boundary of the type.
3457pub trait WrappingMulSubMul<Y = Self, Z = Self, W = Self> {
3458    type Output;
3459
3460    fn wrapping_mul_sub_mul(self, y: Y, z: Z, w: W) -> Self::Output;
3461}
3462
3463/// Subtracts the product of one pair of numbers from the product of another, in place, wrapping
3464/// around at the boundary of the type.
3465pub trait WrappingMulSubMulAssign<Y = Self, Z = Self, W = Self> {
3466    fn wrapping_mul_sub_mul_assign(&mut self, y: Y, z: Z, w: W);
3467}
3468
3469/// Divides a number by another number, wrapping around at the boundary of the type.
3470pub trait WrappingDiv<RHS = Self> {
3471    type Output;
3472
3473    fn wrapping_div(self, other: RHS) -> Self::Output;
3474}
3475
3476/// Divides a number by another number in place, wrapping around at the boundary of the type.
3477pub trait WrappingDivAssign<RHS = Self> {
3478    fn wrapping_div_assign(&mut self, other: RHS);
3479}
3480
3481/// Multiplies two numbers, wrapping around at the boundary of the type.
3482pub trait WrappingMul<RHS = Self> {
3483    type Output;
3484
3485    fn wrapping_mul(self, other: RHS) -> Self::Output;
3486}
3487
3488/// Multiplies a number by another number in place, wrapping around at the boundary of the type.
3489pub trait WrappingMulAssign<RHS = Self> {
3490    fn wrapping_mul_assign(&mut self, other: RHS);
3491}
3492
3493/// Negates a number, wrapping around at the boundary of the type.
3494pub trait WrappingNeg {
3495    type Output;
3496
3497    fn wrapping_neg(self) -> Self::Output;
3498}
3499
3500/// Negates a number in place, wrapping around at the boundary of the type.
3501pub trait WrappingNegAssign {
3502    fn wrapping_neg_assign(&mut self);
3503}
3504
3505/// Raises a number to a power, wrapping around at the boundary of the type.
3506pub trait WrappingPow<RHS> {
3507    type Output;
3508
3509    fn wrapping_pow(self, exp: RHS) -> Self::Output;
3510}
3511
3512/// Raises a number to a power in place, wrapping around at the boundary of the type.
3513pub trait WrappingPowAssign<RHS = Self> {
3514    fn wrapping_pow_assign(&mut self, exp: RHS);
3515}
3516
3517/// Squares a number, wrapping around at the boundary of the type.
3518pub trait WrappingSquare {
3519    type Output;
3520
3521    fn wrapping_square(self) -> Self::Output;
3522}
3523
3524/// Squares a number in place, wrapping around at the boundary of the type.
3525pub trait WrappingSquareAssign {
3526    fn wrapping_square_assign(&mut self);
3527}
3528
3529/// Subtracts two numbers, wrapping around at the boundary of the type.
3530pub trait WrappingSub<RHS = Self> {
3531    type Output;
3532
3533    fn wrapping_sub(self, other: RHS) -> Self::Output;
3534}
3535
3536/// Subtracts a number by another number in place, wrapping around at the boundary of the type.
3537pub trait WrappingSubAssign<RHS = Self> {
3538    fn wrapping_sub_assign(&mut self, other: RHS);
3539}
3540
3541/// Subtracts a number by the product of two other numbers, wrapping around at the boundary of the
3542/// type.
3543pub trait WrappingSubMul<Y = Self, Z = Self> {
3544    type Output;
3545
3546    fn wrapping_sub_mul(self, y: Y, z: Z) -> Self::Output;
3547}
3548
3549/// Subtracts a number by the product of two other numbers, in place, wrapping around at the
3550/// boundary of the type.
3551pub trait WrappingSubMulAssign<Y = Self, Z = Self> {
3552    fn wrapping_sub_mul_assign(&mut self, y: Y, z: Z);
3553}
3554
3555/// Multiplies two numbers, returning the product as a pair of `Self` values.
3556///
3557/// The more significant number always comes first.
3558pub trait XMulYToZZ: Sized {
3559    fn x_mul_y_to_zz(x: Self, y: Self) -> (Self, Self);
3560}
3561
3562/// Adds two numbers, each composed of two `Self` values, returning the sum as a pair of `Self`
3563/// values.
3564///
3565/// The more significant number always comes first. Addition is wrapping, and overflow is not
3566/// indicated.
3567pub trait XXAddYYToZZ: Sized {
3568    fn xx_add_yy_to_zz(x_1: Self, x_0: Self, y_1: Self, y_0: Self) -> (Self, Self);
3569}
3570
3571/// Computes the quotient and remainder of two numbers. The first is composed of two `Self` values,
3572/// and the second of a single one.
3573///
3574/// `x_1` must be less than `y`.
3575pub trait XXDivModYToQR: Sized {
3576    fn xx_div_mod_y_to_qr(x_1: Self, x_0: Self, y: Self) -> (Self, Self);
3577}
3578
3579/// Subtracts two numbers, each composed of two `Self` values, returing the difference as a pair of
3580/// `Self` values.
3581///
3582/// The more significant number always comes first. Subtraction is wrapping, and overflow is not
3583/// indicated.
3584pub trait XXSubYYToZZ: Sized {
3585    fn xx_sub_yy_to_zz(x_1: Self, x_0: Self, y_1: Self, y_0: Self) -> (Self, Self);
3586}
3587
3588/// Adds two numbers, each composed of three `Self` values, returning the sum as a triple of `Self`
3589/// values.
3590///
3591/// The more significant number always comes first. Addition is wrapping, and overflow is not
3592/// indicated.
3593pub trait XXXAddYYYToZZZ: Sized {
3594    fn xxx_add_yyy_to_zzz(
3595        x_2: Self,
3596        x_1: Self,
3597        x_0: Self,
3598        y_2: Self,
3599        y_1: Self,
3600        y_0: Self,
3601    ) -> (Self, Self, Self);
3602}
3603
3604/// Subtracts two numbers, each composed of three `Self` values, returing the difference as a triple
3605/// of `Self` values.
3606///
3607/// The more significant number always comes first. Subtraction is wrapping, and overflow is not
3608/// indicated.
3609pub trait XXXSubYYYToZZZ: Sized {
3610    fn xxx_sub_yyy_to_zzz(
3611        x_2: Self,
3612        x_1: Self,
3613        x_0: Self,
3614        y_2: Self,
3615        y_1: Self,
3616        y_0: Self,
3617    ) -> (Self, Self, Self);
3618}
3619
3620/// Adds two numbers, each composed of four `Self` values, returning the sum as a quadruple of
3621/// `Self` values.
3622///
3623/// The more significant number always comes first. Addition is wrapping, and overflow is not
3624/// indicated.
3625pub trait XXXXAddYYYYToZZZZ: Sized {
3626    #[allow(clippy::too_many_arguments)]
3627    fn xxxx_add_yyyy_to_zzzz(
3628        x_3: Self,
3629        x_2: Self,
3630        x_1: Self,
3631        x_0: Self,
3632        y_3: Self,
3633        y_2: Self,
3634        y_1: Self,
3635        y_0: Self,
3636    ) -> (Self, Self, Self, Self);
3637}