1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Copyright © 2026 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
use crate::natural::Natural;
use crate::natural_polynomial::NaturalPolynomial;
use alloc::vec::Vec;
use malachite_base::num::arithmetic::traits::{
ModInverse, ModIsReduced, ModMulPrecomputed, ModMulPrecomputedAssign,
};
use malachite_base::num::basic::traits::{One, Zero};
use malachite_base::polynomial::{ModIntegral, ModIntegralAssign};
fn assert_reduced(p: &NaturalPolynomial, m: &Natural) {
assert!(
p.mod_is_reduced(m),
"self must be reduced mod m, but {p} has a coefficient >= {m}"
);
}
// The index `k` reduced modulo `m`.
fn index_mod(k: usize, m: &Natural) -> Natural {
Natural::from(k) % m
}
// The coefficients of the integral modulo `m` of the polynomial with coefficients `xs`, which is
// nonempty and reduced modulo `m`. The coefficient of $x^{k-1}$, divided by $k$, goes to $x^k$; a
// zero coefficient stays zero, so its $k$ need not be a unit. All the divisions share one
// inversion. Going down from the top, each nonzero coefficient is first multiplied by the product
// of the larger indices with nonzero coefficients, and then its own index joins the product. Once
// the product has every such index, it is inverted, and going up, each nonzero coefficient is
// multiplied by the inverse, and then its own index is multiplied back into the inverse, dividing
// each coefficient by its own index. The result is not trimmed.
//
// This is `_nmod_poly_integral` from `nmod_poly/integral.c`, FLINT 3.6.0, with a modulus of any
// size, except that FLINT inverts the product of every index, needing all of them to be units.
fn mod_integral_coefficients(xs: Vec<Natural>, m: &Natural) -> Vec<Natural> {
let n = xs.len();
let mut out = Vec::with_capacity(n + 1);
out.push(Natural::ZERO);
out.extend(xs);
if n >= 2 {
let data = <Natural as ModMulPrecomputed<&Natural, &Natural>>::precompute_mod_mul_data(&m);
// The product of the indices above k whose coefficients are nonzero.
let mut product = Natural::ONE % m;
for (k, c) in out.iter_mut().enumerate().skip(2).rev() {
if *c != 0u32 {
c.mod_mul_precomputed_assign(&product, m, &data);
product.mod_mul_precomputed_assign(index_mod(k, m), m, &data);
}
}
let inverse = if product == 0u32 {
None
} else {
(&product).mod_inverse(m)
};
let Some(mut inverse) = inverse else {
panic!(
"The integral modulo m is only defined if every k for which the coefficient of \
x^(k-1) is nonzero is a unit modulo m, but m is {m}"
);
};
for (k, c) in out.iter_mut().enumerate().skip(2) {
if *c != 0u32 {
c.mod_mul_precomputed_assign(&inverse, m, &data);
inverse.mod_mul_precomputed_assign(index_mod(k, m), m, &data);
}
}
}
out
}
fn mod_integral_owned(p: NaturalPolynomial, m: &Natural) -> NaturalPolynomial {
assert_reduced(&p, m);
if p.coefficients.is_empty() {
return p;
}
let mut q = NaturalPolynomial {
coefficients: mod_integral_coefficients(p.coefficients, m),
};
q.trim();
q
}
fn mod_integral_ref(p: &NaturalPolynomial, m: &Natural) -> NaturalPolynomial {
assert_reduced(p, m);
if p.coefficients.is_empty() {
return NaturalPolynomial::ZERO;
}
let mut q = NaturalPolynomial {
coefficients: mod_integral_coefficients(p.coefficients.clone(), m),
};
q.trim();
q
}
impl ModIntegral<Natural> for NaturalPolynomial {
type Output = Self;
/// Computes the integral modulo $m$ of a [`NaturalPolynomial`] whose constant term is zero,
/// taking the polynomial by value and the modulus by value. Its coefficients must already be
/// reduced modulo $m$.
///
/// $$
/// f(p, m) = \int_0^x p(t)\,dt \bmod m = \sum_{i=0}^{n-1} \frac{a_i}{i+1}x^{i+1} \bmod m.
/// $$
///
/// The coefficient of $x^{k-1}$ is divided by $k$ and moved to $x^k$, so every $k$ for which
/// that coefficient is nonzero must be a unit modulo $m$; a zero coefficient stays zero. The
/// divisions share a single modular inversion. The integral of zero is zero, for every $m$.
///
/// # Worst-case complexity
/// $T(n, m) = O((n + \log m) m \log m \log\log m)$
///
/// $M(n, m) = O(nm)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.len()`, and $m$ is
/// `m.significant_bits()`.
///
/// # Panics
/// Panics if `m` is 0, if any coefficient is greater than or equal to `m`, or if, for some $k$,
/// the coefficient of $x^{k-1}$ is nonzero and $k$ is not a unit modulo $m$.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_base::polynomial::ModIntegral;
/// use malachite_nz::natural::Natural;
/// use malachite_nz::natural_polynomial::NaturalPolynomial;
///
/// assert_eq!(
/// NaturalPolynomial::from_str("3*x^2+4*x+5")
/// .unwrap()
/// .mod_integral(Natural::from(7u32))
/// .to_string(),
/// "x^3+2*x^2+5*x"
/// );
/// // Dividing by 3 is multiplying by 5 modulo 7.
/// assert_eq!(
/// NaturalPolynomial::from_str("x^2")
/// .unwrap()
/// .mod_integral(Natural::from(7u32))
/// .to_string(),
/// "5*x^3"
/// );
/// ```
///
/// FLINT has no `fmpz_mod_poly` integral; this is `nmod_poly_integral` from
/// `nmod_poly/integral.c`, FLINT 3.6.0, with a modulus of any size, except that FLINT needs
/// every $k$ from 1 to the degree plus 1 to be a unit modulo $m$, even when the coefficient of
/// $x^{k-1}$ is zero, and aborts otherwise; so, for example, FLINT cannot integrate $x^2$
/// modulo 8, whose integral is $3x^3$.
#[inline]
fn mod_integral(self, m: Natural) -> Self {
mod_integral_owned(self, &m)
}
}
impl ModIntegral<&Natural> for NaturalPolynomial {
type Output = Self;
/// Computes the integral modulo $m$ of a [`NaturalPolynomial`] whose constant term is zero,
/// taking the polynomial by value and the modulus by reference. Its coefficients must already
/// be reduced modulo $m$.
///
/// $$
/// f(p, m) = \int_0^x p(t)\,dt \bmod m = \sum_{i=0}^{n-1} \frac{a_i}{i+1}x^{i+1} \bmod m.
/// $$
///
/// The coefficient of $x^{k-1}$ is divided by $k$ and moved to $x^k$, so every $k$ for which
/// that coefficient is nonzero must be a unit modulo $m$; a zero coefficient stays zero. The
/// divisions share a single modular inversion. The integral of zero is zero, for every $m$.
///
/// # Worst-case complexity
/// $T(n, m) = O((n + \log m) m \log m \log\log m)$
///
/// $M(n, m) = O(nm)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.len()`, and $m$ is
/// `m.significant_bits()`.
///
/// # Panics
/// Panics if `m` is 0, if any coefficient is greater than or equal to `m`, or if, for some $k$,
/// the coefficient of $x^{k-1}$ is nonzero and $k$ is not a unit modulo $m$.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_base::polynomial::ModIntegral;
/// use malachite_nz::natural::Natural;
/// use malachite_nz::natural_polynomial::NaturalPolynomial;
///
/// assert_eq!(
/// NaturalPolynomial::from_str("3*x^2+4*x+5")
/// .unwrap()
/// .mod_integral(&Natural::from(7u32))
/// .to_string(),
/// "x^3+2*x^2+5*x"
/// );
/// // Dividing by 3 is multiplying by 5 modulo 7.
/// assert_eq!(
/// NaturalPolynomial::from_str("x^2")
/// .unwrap()
/// .mod_integral(&Natural::from(7u32))
/// .to_string(),
/// "5*x^3"
/// );
/// ```
///
/// FLINT has no `fmpz_mod_poly` integral; this is `nmod_poly_integral` from
/// `nmod_poly/integral.c`, FLINT 3.6.0, with a modulus of any size, except that FLINT needs
/// every $k$ from 1 to the degree plus 1 to be a unit modulo $m$, even when the coefficient of
/// $x^{k-1}$ is zero, and aborts otherwise; so, for example, FLINT cannot integrate $x^2$
/// modulo 8, whose integral is $3x^3$.
#[inline]
fn mod_integral(self, m: &Natural) -> Self {
mod_integral_owned(self, m)
}
}
impl ModIntegral<Natural> for &NaturalPolynomial {
type Output = NaturalPolynomial;
/// Computes the integral modulo $m$ of a [`NaturalPolynomial`] whose constant term is zero,
/// taking the polynomial by reference and the modulus by value. Its coefficients must already
/// be reduced modulo $m$.
///
/// $$
/// f(p, m) = \int_0^x p(t)\,dt \bmod m = \sum_{i=0}^{n-1} \frac{a_i}{i+1}x^{i+1} \bmod m.
/// $$
///
/// The coefficient of $x^{k-1}$ is divided by $k$ and moved to $x^k$, so every $k$ for which
/// that coefficient is nonzero must be a unit modulo $m$; a zero coefficient stays zero. The
/// divisions share a single modular inversion. The integral of zero is zero, for every $m$.
///
/// # Worst-case complexity
/// $T(n, m) = O((n + \log m) m \log m \log\log m)$
///
/// $M(n, m) = O(nm)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.len()`, and $m$ is
/// `m.significant_bits()`.
///
/// # Panics
/// Panics if `m` is 0, if any coefficient is greater than or equal to `m`, or if, for some $k$,
/// the coefficient of $x^{k-1}$ is nonzero and $k$ is not a unit modulo $m$.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_base::polynomial::ModIntegral;
/// use malachite_nz::natural::Natural;
/// use malachite_nz::natural_polynomial::NaturalPolynomial;
///
/// assert_eq!(
/// (&NaturalPolynomial::from_str("3*x^2+4*x+5").unwrap())
/// .mod_integral(Natural::from(7u32))
/// .to_string(),
/// "x^3+2*x^2+5*x"
/// );
/// // Dividing by 3 is multiplying by 5 modulo 7.
/// assert_eq!(
/// (&NaturalPolynomial::from_str("x^2").unwrap())
/// .mod_integral(Natural::from(7u32))
/// .to_string(),
/// "5*x^3"
/// );
/// ```
///
/// FLINT has no `fmpz_mod_poly` integral; this is `nmod_poly_integral` from
/// `nmod_poly/integral.c`, FLINT 3.6.0, with a modulus of any size, except that FLINT needs
/// every $k$ from 1 to the degree plus 1 to be a unit modulo $m$, even when the coefficient of
/// $x^{k-1}$ is zero, and aborts otherwise; so, for example, FLINT cannot integrate $x^2$
/// modulo 8, whose integral is $3x^3$.
#[inline]
fn mod_integral(self, m: Natural) -> NaturalPolynomial {
mod_integral_ref(self, &m)
}
}
impl ModIntegral<&Natural> for &NaturalPolynomial {
type Output = NaturalPolynomial;
/// Computes the integral modulo $m$ of a [`NaturalPolynomial`] whose constant term is zero,
/// taking the polynomial by reference and the modulus by reference. Its coefficients must
/// already be reduced modulo $m$.
///
/// $$
/// f(p, m) = \int_0^x p(t)\,dt \bmod m = \sum_{i=0}^{n-1} \frac{a_i}{i+1}x^{i+1} \bmod m.
/// $$
///
/// The coefficient of $x^{k-1}$ is divided by $k$ and moved to $x^k$, so every $k$ for which
/// that coefficient is nonzero must be a unit modulo $m$; a zero coefficient stays zero. The
/// divisions share a single modular inversion. The integral of zero is zero, for every $m$.
///
/// # Worst-case complexity
/// $T(n, m) = O((n + \log m) m \log m \log\log m)$
///
/// $M(n, m) = O(nm)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.len()`, and $m$ is
/// `m.significant_bits()`.
///
/// # Panics
/// Panics if `m` is 0, if any coefficient is greater than or equal to `m`, or if, for some $k$,
/// the coefficient of $x^{k-1}$ is nonzero and $k$ is not a unit modulo $m$.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_base::polynomial::ModIntegral;
/// use malachite_nz::natural::Natural;
/// use malachite_nz::natural_polynomial::NaturalPolynomial;
///
/// assert_eq!(
/// (&NaturalPolynomial::from_str("3*x^2+4*x+5").unwrap())
/// .mod_integral(&Natural::from(7u32))
/// .to_string(),
/// "x^3+2*x^2+5*x"
/// );
/// // Dividing by 3 is multiplying by 5 modulo 7.
/// assert_eq!(
/// (&NaturalPolynomial::from_str("x^2").unwrap())
/// .mod_integral(&Natural::from(7u32))
/// .to_string(),
/// "5*x^3"
/// );
/// ```
///
/// FLINT has no `fmpz_mod_poly` integral; this is `nmod_poly_integral` from
/// `nmod_poly/integral.c`, FLINT 3.6.0, with a modulus of any size, except that FLINT needs
/// every $k$ from 1 to the degree plus 1 to be a unit modulo $m$, even when the coefficient of
/// $x^{k-1}$ is zero, and aborts otherwise; so, for example, FLINT cannot integrate $x^2$
/// modulo 8, whose integral is $3x^3$.
#[inline]
fn mod_integral(self, m: &Natural) -> NaturalPolynomial {
mod_integral_ref(self, m)
}
}
impl ModIntegralAssign<Natural> for NaturalPolynomial {
/// Replaces a [`NaturalPolynomial`] with its integral modulo $m$ whose constant term is zero,
/// taking the modulus by value. Its coefficients must already be reduced modulo $m$.
///
/// $$
/// p \gets \int_0^x p(t)\,dt \bmod m = \sum_{i=0}^{n-1} \frac{a_i}{i+1}x^{i+1} \bmod m.
/// $$
///
/// The coefficient of $x^{k-1}$ is divided by $k$ and moved to $x^k$, so every $k$ for which
/// that coefficient is nonzero must be a unit modulo $m$; a zero coefficient stays zero. The
/// divisions share a single modular inversion. The integral of zero is zero, for every $m$.
///
/// # Worst-case complexity
/// $T(n, m) = O((n + \log m) m \log m \log\log m)$
///
/// $M(n, m) = O(nm)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.len()`, and $m$ is
/// `m.significant_bits()`.
///
/// # Panics
/// Panics if `m` is 0, if any coefficient is greater than or equal to `m`, or if, for some $k$,
/// the coefficient of $x^{k-1}$ is nonzero and $k$ is not a unit modulo $m$.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_base::polynomial::ModIntegralAssign;
/// use malachite_nz::natural::Natural;
/// use malachite_nz::natural_polynomial::NaturalPolynomial;
///
/// let mut p = NaturalPolynomial::from_str("3*x^2+4*x+5").unwrap();
/// p.mod_integral_assign(Natural::from(7u32));
/// assert_eq!(p.to_string(), "x^3+2*x^2+5*x");
/// ```
///
/// FLINT has no `fmpz_mod_poly` integral; this is `nmod_poly_integral` from
/// `nmod_poly/integral.c`, FLINT 3.6.0, with a modulus of any size, except that FLINT needs
/// every $k$ from 1 to the degree plus 1 to be a unit modulo $m$, even when the coefficient of
/// $x^{k-1}$ is zero, and aborts otherwise; so, for example, FLINT cannot integrate $x^2$
/// modulo 8, whose integral is $3x^3$.
#[inline]
fn mod_integral_assign(&mut self, m: Natural) {
*self = mod_integral_owned(core::mem::take(self), &m);
}
}
impl ModIntegralAssign<&Natural> for NaturalPolynomial {
/// Replaces a [`NaturalPolynomial`] with its integral modulo $m$ whose constant term is zero,
/// taking the modulus by reference. Its coefficients must already be reduced modulo $m$.
///
/// $$
/// p \gets \int_0^x p(t)\,dt \bmod m = \sum_{i=0}^{n-1} \frac{a_i}{i+1}x^{i+1} \bmod m.
/// $$
///
/// The coefficient of $x^{k-1}$ is divided by $k$ and moved to $x^k$, so every $k$ for which
/// that coefficient is nonzero must be a unit modulo $m$; a zero coefficient stays zero. The
/// divisions share a single modular inversion. The integral of zero is zero, for every $m$.
///
/// # Worst-case complexity
/// $T(n, m) = O((n + \log m) m \log m \log\log m)$
///
/// $M(n, m) = O(nm)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.len()`, and $m$ is
/// `m.significant_bits()`.
///
/// # Panics
/// Panics if `m` is 0, if any coefficient is greater than or equal to `m`, or if, for some $k$,
/// the coefficient of $x^{k-1}$ is nonzero and $k$ is not a unit modulo $m$.
///
/// # Examples
/// ```
/// use core::str::FromStr;
/// use malachite_base::polynomial::ModIntegralAssign;
/// use malachite_nz::natural::Natural;
/// use malachite_nz::natural_polynomial::NaturalPolynomial;
///
/// let mut p = NaturalPolynomial::from_str("3*x^2+4*x+5").unwrap();
/// p.mod_integral_assign(&Natural::from(7u32));
/// assert_eq!(p.to_string(), "x^3+2*x^2+5*x");
/// ```
///
/// FLINT has no `fmpz_mod_poly` integral; this is `nmod_poly_integral` from
/// `nmod_poly/integral.c`, FLINT 3.6.0, with a modulus of any size, except that FLINT needs
/// every $k$ from 1 to the degree plus 1 to be a unit modulo $m$, even when the coefficient of
/// $x^{k-1}$ is zero, and aborts otherwise; so, for example, FLINT cannot integrate $x^2$
/// modulo 8, whose integral is $3x^3$.
#[inline]
fn mod_integral_assign(&mut self, m: &Natural) {
*self = mod_integral_owned(core::mem::take(self), m);
}
}