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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
use flint_sys::{self, fmpz_mod_poly};
use rug::Integer;
use rug_fft;
use serde::de::Deserializer;
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};

use std::cmp::*;
use std::fmt::{self, Debug, Display, Formatter};
use std::mem::MaybeUninit;
use std::ops::*;

/// A polynomial with modular integer coefficients.
///
/// That is, a member of `Z/nZ[X]`.
///
/// # Examples
///
/// See constructors:
///
///    * [`new`](fn.ModPoly.new)
///    * [`interpolate_from_mul_subgroup`](fn.ModPoly.interpolate_from_mul_subgroup)
///
pub struct ModPoly {
    raw: fmpz_mod_poly,
    modulus: Integer,
}

impl ModPoly {
    /// A new polynomial, equal to zero.
    pub fn new(modulus: Integer) -> Self {
        unsafe {
            let mut raw = MaybeUninit::uninit();
            let flint_modulus = flint_sys::gmp_to_flint(modulus.as_raw());
            flint_sys::fmpz_mod_poly_init(raw.as_mut_ptr(), &flint_modulus);
            ModPoly {
                raw: raw.assume_init(),
                modulus,
            }
        }
    }

    /// A new polynomial, equal to `constant`.
    pub fn from_int(modulus: Integer, mut constant: Integer) -> Self {
        constant %= &modulus;
        let mut this = ModPoly::new(modulus);
        this.set_coefficient(0, &constant);
        this
    }

    /// A new polynomial, equal to zero, with room for `n` coefficients.
    pub fn with_capacity(modulus: Integer, n: usize) -> Self {
        unsafe {
            let mut raw = MaybeUninit::uninit();
            let flint_modulus = flint_sys::gmp_to_flint(modulus.as_raw());
            flint_sys::fmpz_mod_poly_init2(raw.as_mut_ptr(), &flint_modulus, n as flint_sys::slong);
            ModPoly {
                raw: raw.assume_init(),
                modulus,
            }
        }
    }

    /// Interpolate a polynomial which agrees with the given values over a multiplicative subgroup
    /// of the prime field with modulus `m`.
    ///
    /// Let `n` be a power of two and the order of the multiplicative subgroup generated by `w`
    /// modulo `m`. Let `ys` be a vector of values at `1`, `w`, `w^2`, ...
    ///
    /// Returns a polynomial `f`, such that for `i` in `0..n`, `f(w^i) = ys[i] mod m`.
    ///
    /// # Panics
    ///
    /// If `n` is not a power of two, or if `w` does not generate a subgroup of order `n`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rug_polynomial::*;
    /// use rug::Integer;
    ///
    /// let m = Integer::from(5);
    /// let w = Integer::from(2);
    /// let ys: Vec<Integer> = vec![2, 3, 0, 4].into_iter().map(Integer::from).collect();
    /// let p = ModPoly::interpolate_from_mul_subgroup(ys, m, &w);
    /// debug_assert_eq!(p.len(), 2);
    /// debug_assert_eq!(p.get_coefficient(0), Integer::from(1));
    /// debug_assert_eq!(p.get_coefficient(1), Integer::from(1));
    /// ```
    pub fn interpolate_from_mul_subgroup(mut ys: Vec<Integer>, m: Integer, w: &Integer) -> Self {
        rug_fft::cooley_tukey_radix_2_intt(&mut ys, &m, w);
        let mut p = ModPoly::with_capacity(m, ys.len());
        for (i, c) in ys.iter().enumerate() {
            p.set_coefficient(i, c);
        }
        p
    }

    /// Returns the minimal-degree monic polynomial with the given roots.
    ///
    /// # Example
    ///
    /// ```
    /// use rug_polynomial::*;
    /// use rug::Integer;
    ///
    /// let p = ModPoly::with_roots(vec![0, 1].into_iter().map(Integer::from), &Integer::from(5));
    /// debug_assert_eq!(p.len(), 3);
    /// debug_assert_eq!(p.get_coefficient(0), Integer::from(0));
    /// debug_assert_eq!(p.get_coefficient(1), Integer::from(4));
    /// debug_assert_eq!(p.get_coefficient(2), Integer::from(1));
    /// ```
    pub fn with_roots(xs: impl IntoIterator<Item = Integer>, m: &Integer) -> Self {
        let mut ps = xs
            .into_iter()
            .map(|x| {
                let mut p = ModPoly::new(m.clone());
                p.set_coefficient_ui(1, 1);
                p.set_coefficient(0, &-x);
                p
            })
            .collect::<Vec<_>>();
        while ps.len() > 1 {
            for i in 0..(ps.len() / 2) {
                let back = ps.pop().unwrap();
                ps[i] *= &back;
            }
        }
        ps.pop().unwrap_or_else(|| {
            let mut p = ModPoly::new(m.clone());
            p.set_coefficient_ui(0, 1);
            p
        })
    }

    /// Reallocates the polynomial to have room for `n` coefficients. Truncates the polynomial if
    /// it has more than `n` coefficients.
    pub fn reserve(&mut self, n: usize) {
        unsafe {
            flint_sys::fmpz_mod_poly_realloc(&mut self.raw, n as flint_sys::slong);
        }
    }

    /// Get the modulus of this polynomial.
    pub fn modulus(&self) -> &Integer {
        &self.modulus
    }

    /// Get the `i`th coefficient
    pub fn get_coefficient(&self, i: usize) -> Integer {
        unsafe {
            let mut c = Integer::new();
            flint_sys::fmpz_mod_poly_get_coeff_mpz(
                c.as_raw_mut(),
                &self.raw,
                i as flint_sys::slong,
            );
            c % &self.modulus
        }
    }

    /// Set the `i`th coefficient to be `c`
    pub fn set_coefficient(&mut self, i: usize, c: &Integer) {
        unsafe {
            flint_sys::fmpz_mod_poly_set_coeff_mpz(
                &mut self.raw,
                i as flint_sys::slong,
                c.as_raw(),
            );
        }
    }

    /// Set the `i`th coefficient to be `c`
    pub fn set_coefficient_ui(&mut self, i: usize, c: usize) {
        unsafe {
            flint_sys::fmpz_mod_poly_set_coeff_ui(
                &mut self.raw,
                i as flint_sys::slong,
                c as flint_sys::ulong,
            );
        }
    }

    /// The number of coefficients in the polynomial. One more than the degree.
    pub fn len(&self) -> usize {
        unsafe { flint_sys::fmpz_mod_poly_length(&self.raw) as usize }
    }

    /// `self = -self`
    pub fn neg(&mut self) {
        unsafe {
            flint_sys::fmpz_mod_poly_neg(&mut self.raw, &self.raw);
        }
    }

    /// `self = self + other`
    pub fn add(&mut self, other: &Self) {
        assert_eq!(self.modulus, other.modulus);
        unsafe {
            flint_sys::fmpz_mod_poly_add(&mut self.raw, &self.raw, &other.raw);
        }
    }

    /// `self = self - other`
    pub fn sub(&mut self, other: &Self) {
        assert_eq!(self.modulus, other.modulus);
        unsafe {
            flint_sys::fmpz_mod_poly_sub(&mut self.raw, &self.raw, &other.raw);
        }
    }

    /// `self = other - self`
    pub fn sub_from(&mut self, other: &Self) {
        assert_eq!(self.modulus, other.modulus);
        unsafe {
            flint_sys::fmpz_mod_poly_sub(&mut self.raw, &other.raw, &self.raw);
        }
    }

    /// `self = self * other`
    pub fn mul(&mut self, other: &Self) {
        assert_eq!(self.modulus, other.modulus);
        unsafe {
            flint_sys::fmpz_mod_poly_mul(&mut self.raw, &self.raw, &other.raw);
        }
    }

    /// Find `q` and `r` such that `self = other * q + r` and `r` has degree less than `other`.
    ///
    /// ## Returns
    ///
    /// `(q, r)`
    pub fn divrem(&self, other: &Self) -> (ModPoly, ModPoly) {
        assert_eq!(self.modulus, other.modulus);
        let mut q = ModPoly::new(self.modulus.clone());
        let mut r = ModPoly::new(self.modulus.clone());
        unsafe {
            flint_sys::fmpz_mod_poly_divrem(&mut q.raw, &mut r.raw, &self.raw, &other.raw);
        }
        (q, r)
    }

    /// `self = self / other`
    pub fn div(&mut self, other: &Self) {
        assert_eq!(self.modulus, other.modulus);
        let mut r = ModPoly::new(self.modulus.clone());
        unsafe {
            flint_sys::fmpz_mod_poly_divrem(&mut self.raw, &mut r.raw, &self.raw, &other.raw);
        }
    }

    /// `self = other / self`
    pub fn div_from(&mut self, other: &Self) {
        assert_eq!(self.modulus, other.modulus);
        let mut r = ModPoly::new(self.modulus.clone());
        unsafe {
            flint_sys::fmpz_mod_poly_divrem(&mut self.raw, &mut r.raw, &other.raw, &self.raw);
        }
    }

    /// `self = self % other`
    pub fn rem(&mut self, other: &Self) {
        assert_eq!(self.modulus, other.modulus);
        let mut q = ModPoly::new(self.modulus.clone());
        unsafe {
            flint_sys::fmpz_mod_poly_divrem(&mut q.raw, &mut self.raw, &self.raw, &other.raw);
        }
    }

    /// `self = other % self`
    pub fn rem_from(&mut self, other: &Self) {
        assert_eq!(self.modulus, other.modulus);
        let mut q = ModPoly::new(self.modulus.clone());
        unsafe {
            flint_sys::fmpz_mod_poly_divrem(&mut q.raw, &mut self.raw, &other.raw, &self.raw);
        }
    }

    /// `self = self * self`
    pub fn sqr(&mut self) {
        unsafe {
            flint_sys::fmpz_mod_poly_sqr(&mut self.raw, &self.raw);
        }
    }
}

impl Clone for ModPoly {
    fn clone(&self) -> Self {
        let mut this = ModPoly::new(self.modulus.clone());
        unsafe {
            flint_sys::fmpz_mod_poly_set(&mut this.raw, &self.raw);
        }
        this
    }
}

impl Drop for ModPoly {
    fn drop(&mut self) {
        unsafe { flint_sys::fmpz_mod_poly_clear(&mut self.raw) }
    }
}

impl PartialEq<ModPoly> for ModPoly {
    fn eq(&self, other: &ModPoly) -> bool {
        unsafe { flint_sys::fmpz_mod_poly_equal(&self.raw, &other.raw) != 0 }
    }
}
impl Eq for ModPoly {}

impl Debug for ModPoly {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("ModPoly")
            .field("modulus", &self.modulus)
            .field(
                "coefficients",
                &(0..self.len())
                    .map(|i| self.get_coefficient(i))
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

impl Display for ModPoly {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let n = self.len();
        let mut first = true;
        for i in 0..n {
            let j = n - i - 1;
            let c = self.get_coefficient(j);
            if c != 0 {
                if !first {
                    write!(f, " + ")?;
                }
                write!(f, "{}", c)?;
                if j != 0 {
                    write!(f, "x^{}", j)?;
                }
                first = false;
            }
        }
        if first {
            write!(f, "0")?;
        }
        Ok(())
    }
}

macro_rules! impl_self_binary {
    ($Big:ty,
     $func:ident,
     $from_func:ident,
     $Trait:ident { $method:ident },
     $TraitAssign:ident { $method_assign:ident }
    ) => {
        // Big + Big
        impl $Trait<$Big> for $Big {
            type Output = $Big;
            #[inline]
            fn $method(mut self, rhs: $Big) -> $Big {
                self.$method_assign(rhs);
                self
            }
        }
        // Big + &Big
        impl $Trait<&$Big> for $Big {
            type Output = $Big;
            #[inline]
            fn $method(mut self, rhs: &$Big) -> $Big {
                self.$method_assign(rhs);
                self
            }
        }
        // &Big + Big
        impl $Trait<$Big> for &$Big {
            type Output = $Big;
            #[inline]
            fn $method(self, mut rhs: $Big) -> $Big {
                <$Big>::$from_func(&mut rhs, self);
                rhs
            }
        }
        // Big += Big
        impl $TraitAssign<$Big> for $Big {
            #[inline]
            fn $method_assign(&mut self, rhs: $Big) {
                <$Big>::$func(self, &rhs)
            }
        }
        // Big += &Big
        impl $TraitAssign<&$Big> for $Big {
            #[inline]
            fn $method_assign(&mut self, rhs: &$Big) {
                <$Big>::$func(self, rhs)
            }
        }
    };
}

macro_rules! impl_int_binary {
    ($Big:ty,
     $Base:ty,
     $func:ident,
     $from_func:ident,
     $lift_func:ident,
     $Trait:ident { $method:ident },
     $TraitAssign:ident { $method_assign:ident }
    ) => {
        // Big + &Base
        impl $Trait<$Base> for $Big {
            type Output = $Big;
            #[inline]
            fn $method(mut self, rhs: $Base) -> $Big {
                let rhs = <$Big>::$lift_func(self.modulus.clone(), rhs);
                <$Big>::$func(&mut self, &rhs);
                self
            }
        }
        // &Base + Big
        impl $Trait<$Big> for $Base {
            type Output = $Big;
            #[inline]
            fn $method(self, mut rhs: $Big) -> $Big {
                let lhs = <$Big>::$lift_func(rhs.modulus.clone(), self);
                <$Big>::$from_func(&mut rhs, &lhs);
                rhs
            }
        }
        // Big += &Base
        impl $TraitAssign<$Base> for $Big {
            #[inline]
            fn $method_assign(&mut self, rhs: $Base) {
                let rhs = <$Big>::$lift_func(self.modulus.clone(), rhs);
                <$Big>::$func(self, &rhs)
            }
        }
    };
}

impl_self_binary!(ModPoly, add, add, Add { add }, AddAssign { add_assign });
impl_int_binary!(
    ModPoly,
    Integer,
    add,
    add,
    from_int,
    Add { add },
    AddAssign { add_assign }
);
impl_self_binary!(
    ModPoly,
    sub,
    sub_from,
    Sub { sub },
    SubAssign { sub_assign }
);
impl_int_binary!(
    ModPoly,
    Integer,
    sub,
    sub_from,
    from_int,
    Sub { sub },
    SubAssign { sub_assign }
);
impl_self_binary!(ModPoly, mul, mul, Mul { mul }, MulAssign { mul_assign });
impl_int_binary!(
    ModPoly,
    Integer,
    mul,
    mul,
    from_int,
    Mul { mul },
    MulAssign { mul_assign }
);
impl_self_binary!(
    ModPoly,
    div,
    div_from,
    Div { div },
    DivAssign { div_assign }
);
impl_int_binary!(
    ModPoly,
    Integer,
    div,
    div_from,
    from_int,
    Div { div },
    DivAssign { div_assign }
);
impl_self_binary!(
    ModPoly,
    rem,
    rem_from,
    Rem { rem },
    RemAssign { rem_assign }
);
impl_int_binary!(
    ModPoly,
    Integer,
    rem,
    rem_from,
    from_int,
    Rem { rem },
    RemAssign { rem_assign }
);

use std::convert::From;

/// Serializable modular polynomial
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ModPolySer {
    pub modulus: Integer,
    pub coefficients: Vec<Integer>,
}

impl From<ModPolySer> for ModPoly {
    fn from(other: ModPolySer) -> ModPoly {
        let mut inner = ModPoly::new(other.modulus.clone());
        for (i, c) in other.coefficients.into_iter().enumerate() {
            inner.set_coefficient(i, &c);
        }
        inner
    }
}

impl From<&ModPoly> for ModPolySer {
    fn from(other: &ModPoly) -> ModPolySer {
        let modulus = other.modulus().clone();
        let coefficients = (0..(other.len()))
            .into_iter()
            .map(|i| other.get_coefficient(i).clone())
            .collect();
        ModPolySer {
            modulus,
            coefficients,
        }
    }
}

impl Serialize for ModPoly {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        ModPolySer::from(self).serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for ModPoly {
    fn deserialize<D>(deserializer: D) -> Result<ModPoly, D::Error>
    where
        D: Deserializer<'de>,
    {
        ModPolySer::deserialize(deserializer).map(ModPoly::from)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn init() {
        let p = Integer::from(17);
        let f = ModPoly::new(p);
        assert_eq!(f.len(), 0);
    }

    #[test]
    fn set_get() {
        let p = Integer::from(17);
        let mut f = ModPoly::new(p);
        f.set_coefficient_ui(0, 1);
        assert_eq!(f.get_coefficient(0), Integer::from(1));
        f.set_coefficient(5, &Integer::from(5));
        for i in 1..5 {
            assert_eq!(f.get_coefficient(i), Integer::from(0));
        }
        assert_eq!(f.get_coefficient(5), Integer::from(5));
    }

    #[test]
    fn add() {
        let p = Integer::from(17);
        let mut f = ModPoly::new(p.clone());
        f.set_coefficient_ui(0, 1);
        let mut g = ModPoly::new(p);
        g.set_coefficient_ui(3, 1);
        let h = f.clone() + g.clone();
        assert_eq!(h.get_coefficient(0), Integer::from(1));
        assert_eq!(h.get_coefficient(1), Integer::from(0));
        assert_eq!(h.get_coefficient(2), Integer::from(0));
        assert_eq!(h.get_coefficient(3), Integer::from(1));
        assert_eq!(h.len(), 4);
        assert_eq!(h, f.clone() + &g);
        assert_eq!(h, &f + g.clone());
        assert_eq!(h, g.clone() + Integer::from(1));
        assert_eq!(h, Integer::from(1) + g.clone());
    }

    #[test]
    fn sub() {
        let p = Integer::from(17);
        let mut f = ModPoly::new(p.clone());
        f.set_coefficient_ui(0, 1);
        let mut g = ModPoly::new(p);
        g.set_coefficient_ui(3, 1);
        let h = f.clone() - g.clone();
        assert_eq!(h.get_coefficient(0), Integer::from(1));
        assert_eq!(h.get_coefficient(1), Integer::from(0));
        assert_eq!(h.get_coefficient(2), Integer::from(0));
        assert_eq!(h.get_coefficient(3), Integer::from(16));
        assert_eq!(h.len(), 4);
        assert_eq!(h, f.clone() - &g);
        assert_eq!(h, &f - g.clone());
        assert_eq!(h, Integer::from(1) - g.clone());
    }

    #[test]
    fn mul() {
        let p = Integer::from(17);
        let mut f = ModPoly::new(p.clone());
        f.set_coefficient_ui(1, 2);
        let mut g = ModPoly::new(p);
        g.set_coefficient_ui(3, 1);
        let h = f.clone() * g.clone();
        assert_eq!(h.get_coefficient(0), Integer::from(0));
        assert_eq!(h.get_coefficient(1), Integer::from(0));
        assert_eq!(h.get_coefficient(2), Integer::from(0));
        assert_eq!(h.get_coefficient(3), Integer::from(0));
        assert_eq!(h.get_coefficient(4), Integer::from(2));
        assert_eq!(h.len(), 5);
        assert_eq!(h, f.clone() * &g);
        assert_eq!(h, &f * g.clone());
        assert_eq!(h, h.clone() * Integer::from(1));
        assert_eq!(h, Integer::from(1) * h.clone());
    }
    #[test]
    fn mul_wrap() {
        let p = Integer::from(17);
        let mut g = ModPoly::new(p);
        g.set_coefficient_ui(3, 1);
        g.set_coefficient_ui(0, 5);
        let h = g.clone() * Integer::from(4);
        assert_eq!(h.get_coefficient(0), Integer::from(3));
        assert_eq!(h.get_coefficient(1), Integer::from(0));
        assert_eq!(h.get_coefficient(2), Integer::from(0));
        assert_eq!(h.get_coefficient(3), Integer::from(4));
        assert_eq!(h.len(), 4);
    }

    #[test]
    fn div() {
        let p = Integer::from(17);
        let mut f = ModPoly::new(p.clone());
        f.set_coefficient_ui(1, 1);
        let mut g = ModPoly::new(p);
        g.set_coefficient_ui(3, 1);
        let h = g.clone() / f.clone();
        assert_eq!(h.get_coefficient(0), Integer::from(0));
        assert_eq!(h.get_coefficient(1), Integer::from(0));
        assert_eq!(h.get_coefficient(2), Integer::from(1));
        assert_eq!(h.len(), 3);
        assert_eq!(h, g.clone() / &f);
        assert_eq!(h, &g / f.clone());
        assert_eq!(h, h.clone() / Integer::from(1));
    }
}