feanor_math/algorithms/poly_factor/
extension.rs

1use crate::algorithms::poly_factor::FactorPolyField;
2use crate::algorithms::poly_gcd::PolyTFracGCDRing;
3use crate::computation::*;
4use crate::reduce_lift::poly_eval::InterpolationBaseRing;
5use crate::field::*;
6use crate::homomorphism::*;
7use crate::algorithms::resultant::ComputeResultantRing;
8use crate::ordered::OrderedRingStore;
9use crate::pid::EuclideanRing;
10use crate::primitive_int::StaticRing;
11use crate::ring::*;
12use crate::rings::extension::FreeAlgebra;
13use crate::rings::extension::FreeAlgebraStore;
14use crate::rings::poly::dense_poly::DensePolyRing;
15use crate::rings::poly::{PolyRing, PolyRingStore};
16use crate::integer::*;
17use crate::MAX_PROBABILISTIC_REPETITIONS;
18use crate::specialization::FiniteRingSpecializable;
19
20#[stability::unstable(feature = "enable")]
21pub struct ProbablyNotSquarefree;
22
23///
24/// Factors a polynomial with coefficients in a field `K` that is a simple, finite-degree
25/// field extension of a base field that supports polynomial factorization. 
26/// 
27/// If the given polynomial is square-free, this will succeed, except with probability
28/// `2^-attempts`. If it is not square-free, this will always fail (i.e. return `Err`). 
29/// 
30#[stability::unstable(feature = "enable")]
31pub fn poly_factor_squarefree_extension<P, Controller>(LX: P, f: &El<P>, attempts: usize, controller: Controller) -> Result<Vec<El<P>>, ProbablyNotSquarefree>
32    where P: RingStore,
33        P::Type: PolyRing + EuclideanRing,
34        <<P::Type as RingExtension>::BaseRing as RingStore>::Type: Field + FreeAlgebra + PolyTFracGCDRing,
35        <<<<P::Type as RingExtension>::BaseRing as RingStore>::Type as RingExtension>::BaseRing as RingStore>::Type: PerfectField + PolyTFracGCDRing + FactorPolyField + InterpolationBaseRing + FiniteRingSpecializable + SelfIso,
36        Controller: ComputationController
37{
38    controller.run_computation(format_args!("factor_ring_ext(pdeg={}, extdeg={})", LX.degree(f).unwrap(), LX.base_ring().rank()), |controller| {
39        let L = LX.base_ring();
40        let K = L.base_ring();
41
42        assert!(LX.base_ring().is_one(LX.lc(f).unwrap()));
43
44        let KX = DensePolyRing::new(K, "X");
45        // Y will take the role of the ring generator `theta`, and `X` remains the indeterminate
46        let KXY = DensePolyRing::new(KX.clone(), "Y");
47
48        let Norm = |f: El<P>| {
49            let f_over_KY = <_ as RingStore>::sum(&KXY,
50                LX.terms(&f).map(|(c, i)| {
51                    let mut result = L.poly_repr(&KXY, c, KX.inclusion());
52                    KXY.inclusion().mul_assign_map(&mut result, KX.pow(KX.indeterminate(), i));
53                    result
54                })
55            );
56            let gen_poly = L.generating_poly(&KXY, KX.inclusion());
57        
58            return <_ as ComputeResultantRing>::resultant(&KXY, f_over_KY, gen_poly);
59        };
60
61        // we want to find `k` such that `N(f(X + k theta))` remains square-free, where `theta` generates `L`;
62        // there are only finitely many `k` that don't work, by the following idea:
63        // Write `f = f1 ... fr` for the factorization of `f`, where `r <= d`. Then `N(f(X + k theta))` is not
64        // square-free, iff there exist `i != j` and `sigma` such that `fi(X + k theta) = sigma(fj(X + k theta)) = sigma(fj)(X + k sigma(theta))`.
65        // Now note that for given `i, j, sigma`, `fi(X + k theta) = sigma(fj)(X + k sigma(theta))` for at most one `k`, as otherwise
66        // `fi(a (k1 - k2) theta) sigma(theta)) = sigma(fj)(a (k1 - k2) sigma(theta))` for all `a in Z` (evaluation is ring hom).
67        //
68        // Now note that `fi(X) - sigma(fj(X))` is a linear combination of `X^m` and `sigma(X^m)`, i.e. of `deg(fi) + deg(fj) <= d`
69        // basic functions. The vectors `(a1 theta)^m, ..., (al theta)^m` for `m <= deg(fi)` and `sigma(a1 theta)^m, ..., sigma(al theta)^m`
70        // for `m <= deg(fj)` are all linearly independent (assuming `a1, ..., al` distinct and `l >= deg(fi) + deg(fj) + 2`), 
71        // thus `char(K) >= d + 2` (or `char(K) = 0`) implies that `fi = fj = 0`, a contradiction.
72        //
73        // Thus we find that there are at most `d(d + 1)/2 * [L : K]` many `k` such that `N(f(X + k theta))` is not squarefree.
74        // This would even work if `k` is not an integer, but any element of `K`. Note that we still require `char(K) >= d + 2` for
75        // the previous paragraph to work.
76
77        let ZZbig = BigIntRing::RING;
78        let characteristic = K.characteristic(&ZZbig).unwrap();
79        // choose bound about twice as large as necessary, so the probability of succeeding is almost 1/2
80        let bound = LX.degree(f).unwrap() * LX.degree(f).unwrap() * L.rank();
81        assert!(ZZbig.is_zero(&characteristic) || ZZbig.is_geq(&characteristic, &int_cast(bound.try_into().unwrap(), ZZbig, StaticRing::<i64>::RING)));
82
83        let mut rng = oorandom::Rand64::new(1);
84
85        for _ in 0..attempts {
86            let k = StaticRing::<i32>::RING.get_uniformly_random(&bound.try_into().unwrap(), || rng.rand_u64());
87            let lin_transform = LX.from_terms([(L.mul(L.canonical_gen(), L.int_hom().map(k)), 0), (L.one(), 1)].into_iter());
88            let f_transformed = LX.evaluate(f, &lin_transform, &LX.inclusion());
89
90            let norm_f_transformed = Norm(LX.clone_el(&f_transformed));
91            log_progress!(controller, "(norm)");
92            let degree = KX.degree(&norm_f_transformed).unwrap();
93            let squarefree_part = <_ as PolyTFracGCDRing>::squarefree_part(&KX, &norm_f_transformed);
94            log_progress!(controller, "(squarefree)");
95
96            if KX.degree(&squarefree_part).unwrap() == degree {
97                let lin_transform_rev = LX.from_terms([(L.mul(L.canonical_gen(), L.int_hom().map(-k)), 0), (L.one(), 1)].into_iter());
98                let (factorization, _unit) = <_ as FactorPolyField>::factor_poly_with_controller(&KX, &squarefree_part, controller.clone());
99                log_progress!(controller, "(factored)");
100                
101                return Ok(factorization.into_iter().map(|(factor, e)| {
102                    assert!(e == 1);
103                    let f_factor = LX.normalize(<_ as PolyTFracGCDRing>::gcd(&LX, &f_transformed, &LX.lifted_hom(&KX, L.inclusion()).map(factor)));
104                    return LX.evaluate(&f_factor, &lin_transform_rev, &LX.inclusion());
105                }).collect());
106            }
107        }
108        return Err(ProbablyNotSquarefree);
109    })
110}
111
112///
113/// Factors a polynomial with coefficients in a field `K` that is a simple, finite-degree
114/// field extension of a base field that supports polynomial factorization. 
115/// 
116#[stability::unstable(feature = "enable")]
117pub fn poly_factor_extension<P, Controller>(poly_ring: P, f: &El<P>, controller: Controller) -> (Vec<(El<P>, usize)>, El<<P::Type as RingExtension>::BaseRing>)
118    where P: RingStore,
119        P::Type: PolyRing + EuclideanRing,
120        <<P::Type as RingExtension>::BaseRing as RingStore>::Type: FreeAlgebra + PerfectField + FiniteRingSpecializable + PolyTFracGCDRing,
121        <<<<P::Type as RingExtension>::BaseRing as RingStore>::Type as RingExtension>::BaseRing as RingStore>::Type: PerfectField + PolyTFracGCDRing + FactorPolyField + InterpolationBaseRing + FiniteRingSpecializable + SelfIso,
122        Controller: ComputationController
123{
124    let KX = &poly_ring;
125    let K = KX.base_ring();
126
127    // We use the approach outlined in Cohen's "a course in computational algebraic number theory".
128    //  - Use square-free reduction to assume wlog that `f` is square-free
129    //  - Observe that the factorization of `f` is the product over `gcd(f, g)` where `g` runs
130    //    through the factors of `N(f)` over `QQ[X]` - assuming that `N(f)` is square-free!
131    //    Here `N(f)` is the "norm" of `f`, i.e.
132    //    the product `prod_sigma sigma(f)` where `sigma` runs through the embeddings `K -> CC`.
133    //  - It is now left to actually compute `N(f)`, which is not so simple as we do not known the
134    //    `sigma`. As it turns out, this is the resultant of `f` and `MiPo(theta)` where `theta`
135    //    generates `K`
136
137    assert!(!KX.is_zero(f));
138    let mut result: Vec<(El<P>, usize)> = Vec::new();
139    for (non_irred_factor, k) in <_ as PolyTFracGCDRing>::power_decomposition(KX, f) {
140        for factor in poly_factor_squarefree_extension(KX, &non_irred_factor, MAX_PROBABILISTIC_REPETITIONS, controller.clone()).ok().unwrap() {
141            if let Some((i, _)) = result.iter().enumerate().filter(|(_, f)| KX.eq_el(&f.0, &factor)).next() {
142                result[i].1 += k;
143            } else {
144                result.push((factor, k));
145            }
146        }
147    }
148    return (result, K.clone_el(KX.coefficient_at(f, 0)));
149}