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
#[cfg(test)]
#[macro_use(quickcheck)]
extern crate quickcheck_macros;

use rug::{integer::IsPrime, Integer};
use std::mem::replace;

fn check_ntt_params(xs: &[Integer], p: &Integer, w: &Integer) {
    debug_assert_ne!(p.is_probably_prime(100), IsPrime::No);
    let n = xs.len();
    for i in 1..n {
        debug_assert_ne!(
            w.clone().pow_mod(&Integer::from(i), p).unwrap(),
            Integer::from(1)
        );
    }
    debug_assert_eq!(
        w.clone().pow_mod(&Integer::from(n), p).unwrap(),
        Integer::from(1)
    );
}

/// Computes, for `i` in `0..n`, `sum_{j=0}^{n-1} w^{ij}*x_j`, modulo `p`.
///
/// # Example
///
/// ```
/// use rug::Integer;
/// use rug_fft::naive_ntt;
///
/// let mut xs = vec![1, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// let p = Integer::from(7);
/// let w = Integer::from(6);
/// naive_ntt(&mut xs, &p, &w);
/// let xs_ex = vec![5, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// assert_eq!(xs, xs_ex);
/// ```
pub fn naive_ntt(xs: &mut [Integer], p: &Integer, w: &Integer) {
    check_ntt_params(xs, p, w);
    let n = xs.len();
    let r = (0..n)
        .map(|i| {
            let wi = w.clone().pow_mod(&Integer::from(i), p).unwrap();
            // Horner
            let mut acc = xs[n - 1].clone();
            for j in (0..(n - 1)).rev() {
                acc *= &wi;
                acc += &xs[j];
                acc %= p;
            }
            acc
        })
        .collect::<Vec<_>>();
    for (i, ii) in r.into_iter().enumerate() {
        xs[i] = ii;
    }
}

/// Computes, for `i` in `0..n`, `x_i` such that `y_i = sum_{j=0}^{n-1} w^{ij}*x_j`, modulo `p`.
///
/// # Example
///
/// ```
/// use rug::Integer;
/// use rug_fft::naive_intt;
///
/// let mut xs = vec![5, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// let p = Integer::from(7);
/// let w = Integer::from(6);
/// naive_intt(&mut xs, &p, &w);
/// let xs_ex = vec![1, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// assert_eq!(xs, xs_ex);
/// ```
pub fn naive_intt(ys: &mut [Integer], p: &Integer, w: &Integer) {
    let n_inv = {
        let mut t = Integer::from(ys.len());
        t.invert_mut(p).unwrap();
        t
    };
    naive_ntt(ys, p, &Integer::from(w.invert_ref(p).unwrap()));
    for y in ys {
        *y *= &n_inv;
        *y %= p;
    }
}

/// Computes, for `i` in `0..n`, `sum_{j=0}^{n-1} w^{ij}*x_j`, modulo `p`.
///
/// Requires `n` to be a power of two, and `w` to be an `n`th root of unity.
///
/// # Example
///
/// ```
/// use rug::Integer;
/// use rug_fft::cooley_tukey_radix_2_ntt;
///
/// let mut xs = vec![1, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// let p = Integer::from(7);
/// let w = Integer::from(6);
/// cooley_tukey_radix_2_ntt(&mut xs, &p, &w);
/// let ys_ex = vec![5, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// assert_eq!(xs, ys_ex);
/// ```
///
/// # Algorithm
///
/// Classic Cooley-Tukey radix-2 DIT FFT. Splits the odd indices into a newly-allocated array.
pub fn cooley_tukey_radix_2_ntt(xs: &mut [Integer], p: &Integer, w: &Integer) {
    assert!(Integer::from(xs.len()).is_power_of_two());
    let mut ws = Vec::with_capacity(xs.len());
    ws.push(Integer::from(1));
    for _ in 0..(xs.len() - 1) {
        ws.push(Integer::from(ws.last().unwrap() * w) % p);
        debug_assert_ne!(ws.last().unwrap(), &Integer::from(1));
    }
    debug_assert_eq!(w.clone() * ws.last().unwrap() % p, Integer::from(1));
    cooley_tukey_radix_2_ntt_h(xs, p, &ws, 1);
}

/// Computes, for `i` in `0..n`, `x_i` such that `y_i = sum_{j=0}^{n-1} w^{ij}*x_j`, modulo `p`.
///
/// Requires `n` to be a power of two, and `w` to be an `n`th root of unity.
///
/// # Example
///
/// ```
/// use rug::Integer;
/// use rug_fft::cooley_tukey_radix_2_intt;
///
/// let mut xs = vec![5, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// let p = Integer::from(7);
/// let w = Integer::from(6);
/// cooley_tukey_radix_2_intt(&mut xs, &p, &w);
/// let ys_ex = vec![1, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// assert_eq!(xs, ys_ex);
/// ```
pub fn cooley_tukey_radix_2_intt(ys: &mut [Integer], p: &Integer, w: &Integer) {
    let n_inv = {
        let mut t = Integer::from(ys.len());
        t.invert_mut(p).unwrap();
        t
    };
    cooley_tukey_radix_2_ntt(ys, p, &Integer::from(w.invert_ref(p).unwrap()));
    for y in ys {
        *y *= &n_inv;
        *y %= p;
    }
}

fn log2(x: usize) -> Option<usize> {
    let mut t = 1;
    let mut ct = 0;
    while t < x {
        t <<= 1;
        ct += 1;
    }
    if t == x { Some(ct) } else { None }
}

// Reverse the low-order n bits of x. Assumes x fits in n bits.
fn reverse_bits(x: u32, n: u32) -> u32 {
    use std::mem::size_of;
    let u32bits = size_of::<u32>() as u32 * 8;
    x.reverse_bits() >> (u32bits - n)
}

/// Computes, for `i` in `0..n`, `sum_{j=0}^{n-1} w^{ij}*x_j`, modulo `p`.
///
/// Requires `n` to be a power of two, and `w` to be an `n`th root of unity.
///
/// # Example
///
/// ```
/// use rug::Integer;
/// use rug_fft::bit_rev_radix_2_ntt;
///
/// let mut xs = vec![1, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// let p = Integer::from(7);
/// let w = Integer::from(6);
/// bit_rev_radix_2_ntt(&mut xs, &p, &w);
/// let ys_ex = vec![5, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// assert_eq!(xs, ys_ex);
/// ```
///
/// # Algorithm
///
/// Starts by doing a bit-reversal permutation on the input. Then applies blocks of successively
/// wider butterfly transformations.
///
/// Based on [this
/// pseudocode](https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#Data_reordering,_bit_reversal,_and_in-place_algorithms).
pub fn bit_rev_radix_2_ntt(xs: &mut [Integer], p: &Integer, w: &Integer) {
    assert!(Integer::from(xs.len()).is_power_of_two());
    let n = xs.len();
    assert!(n < u32::MAX as usize);
    let log_n = log2(n).expect("need a power of two length") as u32;
    if log_n == 0 {
        return
    }

    for i in 0..(n as u32) {
        let j = reverse_bits(i, log_n);
        if i < j {
            xs.swap(i as usize, j as usize);
        }
    }

    let mut m = 1;
    for _ in 0..log_n {
        // Sweep the entries in 2*m-sized blocks
        let w_m = w.clone().pow_mod(&Integer::from(n / (2*m)), p).expect("p not prime");
        let mut k = 0;
        while k < n {
            // The block starting at index k
            let mut ww = Integer::from(1);
            for j in 0..m {
                // Butterfly
                //
                // x[a]    --->   x[a]
                //         \ / +
                //         / \ -
                // x[b]*w  --->   x[b]
                let a = (k + j) as usize;
                let b = (k + j + m) as usize;
                let mut t = xs[b].clone();
                t *= &ww;
                t %= p;

                xs[b] = xs[a].clone();
                xs[a] += &t;
                if &xs[a] > p {
                    xs[a] -= p;
                }
                xs[b] -= &t;
                if xs[b] < 0 {
                    xs[b] += p;
                }

                ww *= &w_m;
                ww %= p;
            }
            k += 2 * m;
        }
        m *= 2;
    }
}

/// Computes, for `i` in `0..n`, `x_i` such that `y_i = sum_{j=0}^{n-1} w^{ij}*x_j`, modulo `p`.
///
/// Requires `n` to be a power of two, and `w` to be an `n`th root of unity.
///
/// # Example
///
/// ```
/// use rug::Integer;
/// use rug_fft::bit_rev_radix_2_intt;
///
/// let mut xs = vec![5, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// let p = Integer::from(7);
/// let w = Integer::from(6);
/// bit_rev_radix_2_intt(&mut xs, &p, &w);
/// let ys_ex = vec![1, 4]
///     .into_iter()
///     .map(Integer::from)
///     .collect::<Vec<_>>();
/// assert_eq!(xs, ys_ex);
/// ```
pub fn bit_rev_radix_2_intt(ys: &mut [Integer], p: &Integer, w: &Integer) {
    let n_inv = {
        let mut t = Integer::from(ys.len());
        t.invert_mut(p).unwrap();
        t
    };
    bit_rev_radix_2_ntt(ys, p, &Integer::from(w.invert_ref(p).unwrap()));
    for y in ys {
        *y *= &n_inv;
        *y %= p;
    }
}

fn cooley_tukey_radix_2_ntt_h(xs: &mut [Integer], p: &Integer, ws: &[Integer], wi: usize) {
    let n = xs.len();
    if n < 2 {
        return;
    }

    // Split
    let mut odd = (0..n / 2)
        .map(|i| replace(&mut xs[2 * i + 1], Integer::new()))
        .collect::<Vec<_>>();
    for i in 1..n / 2 {
        xs.swap(i, 2 * i);
    }

    // Recurse
    cooley_tukey_radix_2_ntt_h(&mut odd, p, ws, 2 * wi);
    cooley_tukey_radix_2_ntt_h(&mut xs[..n / 2], p, ws, 2 * wi);

    // Merge
    for (i, o) in odd.into_iter().enumerate() {
        xs[n / 2 + i] = xs[i].clone();
        let f = o * &ws[wi * i % ws.len()] % p;
        xs[i] += &f;
        xs[i] %= p;
        xs[n / 2 + i] -= &f;
        xs[n / 2 + i] += p;
        xs[n / 2 + i] %= p;
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use quickcheck::{Arbitrary, Gen};

    // Thanks: https://www.nayuki.io/page/number-theoretic-transform-integer-dft
    #[test]
    fn naive_ntt_5() {
        let mut xs = vec![6, 0, 10, 7, 2]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let p = Integer::from(11);
        let w = Integer::from(3);
        naive_ntt(&mut xs, &p, &w);
        let ys_ex = vec![3, 7, 0, 5, 4]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        assert_eq!(xs, ys_ex);
    }

    #[test]
    fn naive_ntt_8() {
        let mut xs = vec![4, 1, 4, 2, 1, 3, 5, 6]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let p = Integer::from(673);
        let w = Integer::from(326);
        naive_ntt(&mut xs, &p, &w);
        let ys_ex = vec![26, 338, 228, 115, 2, 457, 437, 448]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        assert_eq!(xs, ys_ex);
    }

    #[test]
    fn naive_ntt_2() {
        let mut xs = vec![1, 4]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let p = Integer::from(7);
        let w = Integer::from(6);
        naive_ntt(&mut xs, &p, &w);
        let ys_ex = vec![5, 4]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        assert_eq!(xs, ys_ex);
    }

    #[test]
    fn naive_round_trip_8() {
        let mut xs = vec![4, 1, 4, 2, 1, 3, 5, 6]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let xs2 = xs.clone();
        let p = Integer::from(673);
        let w = Integer::from(326);
        naive_ntt(&mut xs, &p, &w);
        naive_intt(&mut xs, &p, &w);
        assert_eq!(xs, xs2);
    }

    #[test]
    fn ct_ntt_2() {
        let xs = vec![1, 4]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let p = Integer::from(7);
        let w = Integer::from(6);
        let mut ys = xs;
        cooley_tukey_radix_2_ntt(&mut ys, &p, &w);
        let ys_ex = vec![5, 4]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        assert_eq!(ys, ys_ex);
    }

    #[test]
    fn ct_ntt_8() {
        let xs = vec![4, 1, 4, 2, 1, 3, 5, 6]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let p = Integer::from(673);
        let w = Integer::from(326);
        let mut ys = xs;
        cooley_tukey_radix_2_ntt(&mut ys, &p, &w);
        let ys_ex = vec![26, 338, 228, 115, 2, 457, 437, 448]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        assert_eq!(ys, ys_ex);
    }

    #[test]
    fn ct_round_trip_8() {
        let xs = vec![4, 1, 4, 2, 1, 3, 5, 6]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let mut ys = xs.clone();
        let p = Integer::from(673);
        let w = Integer::from(326);
        cooley_tukey_radix_2_ntt(&mut ys, &p, &w);
        cooley_tukey_radix_2_intt(&mut ys, &p, &w);
        assert_eq!(xs, ys);
    }

    #[test]
    fn br_ntt_2() {
        let xs = vec![1, 4]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let p = Integer::from(7);
        let w = Integer::from(6);
        let mut ys = xs;
        bit_rev_radix_2_ntt(&mut ys, &p, &w);
        let ys_ex = vec![5, 4]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        assert_eq!(ys, ys_ex);
    }

    #[test]
    fn br_ntt_8() {
        let xs = vec![4, 1, 4, 2, 1, 3, 5, 6]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        let p = Integer::from(673);
        let w = Integer::from(326);
        let mut ys = xs;
        bit_rev_radix_2_ntt(&mut ys, &p, &w);
        let ys_ex = vec![26, 338, 228, 115, 2, 457, 437, 448]
            .into_iter()
            .map(Integer::from)
            .collect::<Vec<_>>();
        assert_eq!(ys, ys_ex);
    }

    #[derive(Clone, Debug)]
    struct NttInput {
        p: Integer,
        w: Integer,
        xs: Vec<Integer>,
    }

    impl Arbitrary for NttInput {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            let p = Integer::from(673);
            let mut w = Integer::from(118); // Order 32
            let lg_size = g.next_u32() % 6;
            let size = 1 << lg_size;
            w = w.pow_mod(&Integer::from(32 / size), &p).unwrap();
            let xs = std::iter::repeat_with(|| Integer::from(g.next_u32()) % &p)
                .take(size)
                .collect::<Vec<_>>();
            NttInput { p, w, xs }
        }
    }

    #[quickcheck]
    fn ct_round_trip_quickcheck(input: NttInput) -> bool {
        let mut ys = input.xs.clone();
        cooley_tukey_radix_2_ntt(&mut ys, &input.p, &input.w);
        cooley_tukey_radix_2_intt(&mut ys, &input.p, &input.w);
        ys == input.xs
    }

    #[quickcheck]
    fn br_round_trip_quickcheck(input: NttInput) -> bool {
        let mut ys = input.xs.clone();
        bit_rev_radix_2_ntt(&mut ys, &input.p, &input.w);
        bit_rev_radix_2_intt(&mut ys, &input.p, &input.w);
        ys == input.xs
    }
}