feanor-math 3.5.18

A library for number theory, providing implementations for arithmetic in various rings and algorithms working on them.
Documentation
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
use dense_poly::DensePolyRing;
use squarefree_part::poly_power_decomposition_monic_local;

use super::{evaluate_aX, unevaluate_aX};
use crate::MAX_PROBABILISTIC_REPETITIONS;
use crate::algorithms::poly_gcd::hensel::*;
use crate::algorithms::poly_gcd::*;
use crate::seq::*;

const HOPE_FOR_SQUAREFREE_TRIES: usize = 3;

/// Describes the relationship of `f, g, gcd(f, g)` modulo a single maximal ideal
#[derive(PartialEq, Eq)]
struct Signature {
    /// the degree of `gcd(f, g) mod m`
    gcd_deg: usize,
    /// whether `f/d` is coprime to `d`, where `d = gcd(f, g) mod m`
    coprime_to_f_over_d: bool,
}

/// Tries to compute the gcd of monic polynomials `f, g in R[X]` over `Frac(R)` locally, without
/// ever explicitly working in `Frac(R)`. This function will fail in two cases
///  - both `d, f/d` and `d, g/d` are not coprime
///  - the gcd of `f, g` cannot be reconstructed from its reduction modulo `p^e`, where `e` is (as
///    usual) the result of the "heuristic exponent", scaled exponentially by the current attempt
/// If neither is the case, this function is likely to succeed
///
/// More precisely, computes some `d in R[X]` of maximal degree with the property that there exists
/// `a in R \ {0}` such that `d | af, ag`.
fn poly_gcd_monic_coprime_local<P, F, Controller>(
    poly_ring: P,
    f: &El<P>,
    g: &El<P>,
    rng: F,
    current_attempt: usize,
    controller: Controller,
) -> Option<El<P>>
where
    P: RingStore + Copy,
    P::Type: PolyRing + DivisibilityRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PolyGCDLocallyDomain,
    F: FnMut() -> u64,
    Controller: ComputationController,
{
    assert!(poly_ring.base_ring().is_one(poly_ring.lc(f).unwrap()));
    assert!(poly_ring.base_ring().is_one(poly_ring.lc(g).unwrap()));

    let ring = poly_ring.base_ring().get_ring();

    let ideal = ring.random_suitable_ideal(rng);
    let heuristic_e = ring.heuristic_exponent(&ideal, poly_ring.degree(f).unwrap(), poly_ring.terms(f).map(|(c, _)| c));
    assert!(heuristic_e >= 1);
    let e = (heuristic_e as f64 * INCREASE_EXPONENT_PER_ATTEMPT_CONSTANT.powi(current_attempt.try_into().unwrap()))
        .floor() as usize;
    let reduction = ReductionContext::new(ring, &ideal, e);

    log_progress!(
        controller,
        "(mod={}^{})(parts={})",
        IdealDisplayWrapper::new(ring, &ideal),
        e,
        reduction.len()
    );

    let mut signature: Option<Signature> = None;
    let mut poly_rings_mod_me = Vec::new();
    let mut gcds_mod_me = Vec::new();

    for idx in 0..reduction.len() {
        let S_to_F = reduction.intermediate_ring_to_field_reduction(idx);
        let F_iso = reduction.base_ring_to_field_iso(idx);
        let F = F_iso.codomain();
        let R_to_F = (&F_iso).compose(reduction.main_ring_to_field_reduction(idx));
        let FX = DensePolyRing::new(&F, "X");
        let RX_to_FX = FX.lifted_hom(poly_ring, &R_to_F);

        let d = controller.clone().run_computation(format_args!("local_gcd."), |_| {
            FX.normalize(FX.ideal_gen(&RX_to_FX.map_ref(f), &RX_to_FX.map_ref(g)))
        });

        let f_over_d = FX.checked_div(&RX_to_FX.map_ref(f), &d).unwrap();
        let g_over_d = FX.checked_div(&RX_to_FX.map_ref(g), &d).unwrap();
        let deg_d = FX.degree(&d).unwrap();
        let (poly, factor1, factor2, new_signature) = if FX.is_unit(&FX.ideal_gen(&d, &f_over_d)) {
            (
                f,
                d,
                f_over_d,
                Signature {
                    gcd_deg: deg_d,
                    coprime_to_f_over_d: true,
                },
            )
        } else if FX.is_unit(&FX.ideal_gen(&d, &g_over_d)) {
            (
                g,
                d,
                g_over_d,
                Signature {
                    gcd_deg: deg_d,
                    coprime_to_f_over_d: false,
                },
            )
        } else {
            log_progress!(controller, "(not_coprime)");
            return None;
        };
        if signature.is_some() && signature.as_ref().unwrap() != &new_signature {
            log_progress!(controller, "(signature_mismatch)");
            return None;
        }
        signature = Some(new_signature);
        let SX = DensePolyRing::new(*S_to_F.domain(), "X");
        let RX_to_SX = SX.lifted_hom(poly_ring, reduction.main_ring_to_intermediate_ring_reduction(idx));

        let factors = [factor1, factor2];
        let [d, _] = hensel_lift_factorization(
            &S_to_F,
            &SX,
            &FX,
            &RX_to_SX.map_ref(poly),
            &factors[..],
            controller.clone(),
        )
        .try_into()
        .ok()
        .unwrap();

        poly_rings_mod_me.push(SX);
        gcds_mod_me.push(d);
    }

    let signature = signature.unwrap();
    let mut result = controller.clone().run_computation(format_args!("reconstruct."), |_| {
        poly_ring.from_terms((0..=signature.gcd_deg).map(|i| {
            (
                reduction.reconstruct_ring_el(
                    (0..reduction.len()).map_fn(|j| poly_rings_mod_me[j].coefficient_at(&gcds_mod_me[j], i)),
                ),
                i,
            )
        }))
    });

    let divides_f_and_g = controller
        .clone()
        .run_computation(format_args!("check_division."), |_| {
            poly_ring.divides(f, &result) && poly_ring.divides(g, &result)
        });
    if !divides_f_and_g {
        log_progress!(controller, "(no_divisor)");
        return None;
    } else {
        _ = poly_ring.balance_poly(&mut result);
        return Some(result);
    }
}

/// Tries to compute the gcd of polynomials `f, g in R[X]` over `Frac(R)` locally, without ever
/// explicitly working in `Frac(R)`. This function is likely to succeed if either `d, f/d` or `d,
/// g/d` are coprime (over `Frac(R)`), but will never succeed if neither is the case.
///
/// More precisely, computes some `d in R[X]` of maximal degree with the property that there exists
/// `a in R \ {0}` such that `d | af, ag`.
fn poly_gcd_coprime_local<P, F, Controller>(
    poly_ring: P,
    mut f: El<P>,
    mut g: El<P>,
    rng: F,
    attempt: usize,
    controller: Controller,
) -> Option<El<P>>
where
    P: RingStore + Copy,
    P::Type: PolyRing + DivisibilityRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PolyGCDLocallyDomain,
    F: FnMut() -> u64,
    Controller: ComputationController,
{
    if poly_ring.is_zero(&f) {
        return Some(poly_ring.clone_el(&g));
    } else if poly_ring.is_zero(&g) {
        return Some(poly_ring.clone_el(&f));
    }
    _ = poly_ring.balance_poly(&mut f);
    _ = poly_ring.balance_poly(&mut g);
    let lcf = poly_ring.base_ring().clone_el(poly_ring.lc(&f).unwrap());
    let lcg = poly_ring.base_ring().clone_el(poly_ring.lc(&g).unwrap());
    let ring = poly_ring.base_ring();
    let a = ring.mul_ref(&lcf, &lcg);
    let f_monic = evaluate_aX(poly_ring, &poly_ring.inclusion().mul_map(f, lcg), &a);
    let g_monic = evaluate_aX(poly_ring, &poly_ring.inclusion().mul_map(g, lcf), &a);

    let d_monic = poly_gcd_monic_coprime_local(poly_ring, &f_monic, &g_monic, rng, attempt, controller)?;

    let mut result = unevaluate_aX(poly_ring, &d_monic, &a);
    _ = poly_ring.balance_poly(&mut result);
    return Some(result);
}

/// Computes the gcd of monic polynomials `f, g in R[X]` over `Frac(R)` locally, without ever
/// explicitly working in `Frac(R)`.
///
/// More precisely, computes some `d in R[X]` of maximal degree with the property that there exists
/// `a in R \ {0}` such that `d | af, ag`.
///
/// The result can be assumed to be "balanced", according to the contract of
/// [`DivisibilityRing::balance_factor()`] of the underlying ring.
#[stability::unstable(feature = "enable")]
pub fn poly_gcd_monic_local<'a, P, Controller>(
    poly_ring: P,
    mut f: &'a El<P>,
    mut g: &'a El<P>,
    controller: Controller,
) -> El<P>
where
    P: RingStore + Copy,
    P::Type: PolyRing + DivisibilityRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PolyGCDLocallyDomain,
    Controller: ComputationController,
{
    assert!(poly_ring.base_ring().is_one(poly_ring.lc(f).unwrap()));
    assert!(poly_ring.base_ring().is_one(poly_ring.lc(g).unwrap()));

    controller.run_computation(
        format_args!(
            "gcd_local(deg_l={}, deg_r={})",
            poly_ring.degree(f).unwrap(),
            poly_ring.degree(g).unwrap()
        ),
        |controller| {
            let mut rng = oorandom::Rand64::new(1);
            for attempt in 0..HOPE_FOR_SQUAREFREE_TRIES {
                if let Some(result) =
                    poly_gcd_monic_coprime_local(poly_ring, f, g, || rng.rand_u64(), attempt, controller.clone())
                {
                    return result;
                }
            }
            if poly_ring.degree(g).unwrap_or(0) <= poly_ring.degree(f).unwrap_or(0) {
                std::mem::swap(&mut f, &mut g);
            }
            let f_power_decomposition = poly_power_decomposition_monic_local(poly_ring, f, controller.clone());
            let mut g = poly_ring.clone_el(g);
            let mut d = poly_ring.one();

            'extract_part_i: for i in 1.. {
                let squarefree_part_i = poly_ring.prod(
                    f_power_decomposition
                        .iter()
                        .filter(|(_, j)| *j >= i)
                        .map(|(fj, _)| poly_ring.clone_el(fj)),
                );
                if poly_ring.is_one(&squarefree_part_i) {
                    return d;
                }
                for attempt in 0..MAX_PROBABILISTIC_REPETITIONS {
                    if let Some(di) = poly_gcd_coprime_local(
                        poly_ring,
                        poly_ring.clone_el(&squarefree_part_i),
                        poly_ring.clone_el(&g),
                        || rng.rand_u64(),
                        attempt,
                        controller.clone(),
                    ) {
                        g = poly_ring.checked_div(&g, &di).unwrap();
                        poly_ring.mul_assign(&mut d, di);
                        continue 'extract_part_i;
                    }
                }
                unreachable!()
            }
            unreachable!()
        },
    )
}

/// Computes the gcd of polynomials `f, g in R[X]` over `Frac(R)` locally, without ever
/// explicitly working in `Frac(R)`.
///
/// More precisely, computes some `d in R[X]` of maximal degree with the property that there exists
/// `a in R \ {0}` such that `d | af, ag`.
///
/// The result can be assumed to be "balanced", according to the contract of
/// [`DivisibilityRing::balance_factor()`] of the underlying ring.
#[stability::unstable(feature = "enable")]
pub fn poly_gcd_local<P, Controller>(poly_ring: P, mut f: El<P>, mut g: El<P>, controller: Controller) -> El<P>
where
    P: RingStore + Copy,
    P::Type: PolyRing + DivisibilityRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PolyGCDLocallyDomain,
    Controller: ComputationController,
{
    if poly_ring.is_zero(&f) {
        return poly_ring.clone_el(&g);
    } else if poly_ring.is_zero(&g) {
        return poly_ring.clone_el(&f);
    }
    _ = poly_ring.balance_poly(&mut f);
    _ = poly_ring.balance_poly(&mut g);
    let lcf = poly_ring.base_ring().clone_el(poly_ring.lc(&f).unwrap());
    let lcg = poly_ring.base_ring().clone_el(poly_ring.lc(&g).unwrap());
    let ring = poly_ring.base_ring();
    let a = ring.mul_ref(&lcf, &lcg);
    let f_monic = evaluate_aX(poly_ring, &poly_ring.inclusion().mul_map(f, lcg), &a);
    let g_monic = evaluate_aX(poly_ring, &poly_ring.inclusion().mul_map(g, lcf), &a);

    let d_monic = poly_gcd_monic_local(poly_ring, &f_monic, &g_monic, controller);

    let mut result = unevaluate_aX(poly_ring, &d_monic, &a);
    _ = poly_ring.balance_poly(&mut result);
    if let Some(lc_inv) = poly_ring.base_ring().invert(poly_ring.lc(&result).unwrap()) {
        poly_ring.inclusion().mul_assign_map(&mut result, lc_inv);
    }
    return result;
}

#[cfg(test)]
use crate::RANDOM_TEST_INSTANCE_COUNT;
#[cfg(test)]
use crate::algorithms::poly_gcd::make_primitive;
#[cfg(test)]
use crate::integer::*;

#[test]
fn test_poly_gcd_local() {
    let ring = BigIntRing::RING;
    let poly_ring = DensePolyRing::new(ring, "X");
    let irred_polys = poly_ring.with_wrapped_indeterminate(|X| {
        [
            X - 1,
            X + 1,
            X.pow_ref(2) + X + 1,
            X.pow_ref(3) + X + 100,
            X.pow_ref(4) + X.pow_ref(3) + X.pow_ref(2) + X + 1,
        ]
    });
    let poly = |powers: [usize; 5], scale: i32| {
        poly_ring.int_hom().mul_map(
            poly_ring.prod(
                powers
                    .iter()
                    .zip(irred_polys.iter())
                    .map(|(e, f)| poly_ring.pow(poly_ring.clone_el(f), *e)),
            ),
            scale,
        )
    };

    assert_el_eq!(
        &poly_ring,
        poly([1, 0, 0, 0, 0], 1),
        poly_gcd_local(
            &poly_ring,
            poly([1, 0, 1, 0, 0], 1),
            poly([1, 0, 0, 1, 0], 2),
            TEST_LOG_PROGRESS
        )
    );

    assert_el_eq!(
        &poly_ring,
        poly([1, 0, 1, 0, 1], 1),
        poly_gcd_local(
            &poly_ring,
            poly([1, 1, 1, 0, 1], 20),
            poly([1, 0, 1, 1, 1], 12),
            TEST_LOG_PROGRESS
        )
    );

    assert_el_eq!(
        &poly_ring,
        poly([1, 0, 2, 0, 1], 1),
        poly_gcd_local(
            &poly_ring,
            poly([1, 1, 3, 0, 1], 20),
            poly([3, 0, 2, 0, 3], 12),
            TEST_LOG_PROGRESS
        )
    );

    assert_el_eq!(
        &poly_ring,
        poly([1, 0, 0, 5, 0], 1),
        poly_gcd_local(
            &poly_ring,
            poly([2, 1, 3, 5, 1], 20),
            poly([1, 0, 0, 7, 0], 12),
            TEST_LOG_PROGRESS
        )
    );
}

#[test]
fn random_test_poly_gcd_local() {
    let ring = BigIntRing::RING;
    let poly_ring = dense_poly::DensePolyRing::new(ring, "X");
    let mut rng = oorandom::Rand64::new(1);
    let bound = ring.int_hom().map(10000);
    for _ in 0..RANDOM_TEST_INSTANCE_COUNT {
        let f = poly_ring.from_terms((0..=20).map(|i| (ring.get_uniformly_random(&bound, || rng.rand_u64()), i)));
        let g = poly_ring.from_terms((0..=20).map(|i| (ring.get_uniformly_random(&bound, || rng.rand_u64()), i)));
        let h = poly_ring.from_terms((0..=10).map(|i| (ring.get_uniformly_random(&bound, || rng.rand_u64()), i)));
        // println!("Testing gcd on ({}) * ({}) and ({}) * ({})", poly_ring.format(&f),
        // poly_ring.format(&h), poly_ring.format(&g), poly_ring.format(&h));
        let lhs = poly_ring.mul_ref(&f, &h);
        let rhs = poly_ring.mul_ref(&g, &h);
        let gcd = make_primitive(
            &poly_ring,
            &poly_gcd_local(
                &poly_ring,
                poly_ring.clone_el(&lhs),
                poly_ring.clone_el(&rhs),
                TEST_LOG_PROGRESS,
            ),
        )
        .0;
        // println!("Result {}", poly_ring.format(&gcd));

        assert!(poly_ring.divides(&lhs, &gcd));
        assert!(poly_ring.divides(&rhs, &gcd));
        assert!(poly_ring.divides(&gcd, &make_primitive(&poly_ring, &h).0));
    }
}