1 /*
2 Copyright (C) 2007, 2008 William Hart
3 Copyright (C) 2011 Sebastian Pancratz
4
5 This file is part of FLINT.
6
7 FLINT is free software: you can redistribute it and/or modify it under
8 the terms of the GNU Lesser General Public License (LGPL) as published
9 by the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version. See <http://www.gnu.org/licenses/>.
11 */
12
13 #include <stdlib.h>
14 #include <gmp.h>
15 #include "flint.h"
16 #include "mpn_extras.h"
17 #include "nmod_vec.h"
18 #include "nmod_poly.h"
19
20 mp_limb_t
_nmod_poly_resultant_euclidean(mp_srcptr poly1,slong len1,mp_srcptr poly2,slong len2,nmod_t mod)21 _nmod_poly_resultant_euclidean(mp_srcptr poly1, slong len1,
22 mp_srcptr poly2, slong len2, nmod_t mod)
23 {
24 if (poly1 == poly2)
25 {
26 return 0;
27 }
28 else if (len2 == 1)
29 {
30 if (len1 == 1)
31 {
32 return 1;
33 }
34 else if (len1 == 2)
35 {
36 return poly2[0];
37 }
38 else
39 {
40 return n_powmod2_ui_preinv(poly2[0], len1 - 1, mod.n, mod.ninv);
41 }
42 }
43 else /* len1 >= len2 >= 2 */
44 {
45 mp_limb_t res = 1;
46
47 mp_ptr u, v, r, t, w;
48 slong l0, l1, l2;
49 mp_limb_t lc;
50
51 w = _nmod_vec_init(3 * len1);
52 u = w;
53 v = w + len1;
54 r = v + len1;
55
56 _nmod_vec_set(u, poly1, len1);
57 _nmod_vec_set(v, poly2, len2);
58 l1 = len1;
59 l2 = len2;
60
61 do
62 {
63 l0 = l1;
64 l1 = l2;
65 lc = v[l1 - 1];
66
67 _nmod_poly_rem(r, u, l0, v, l1, mod);
68 l2 = l1 - 1;
69 MPN_NORM(r, l2);
70 {
71 t = u;
72 u = v;
73 v = r;
74 r = t;
75 }
76
77 if (l2 >= 1)
78 {
79 lc = n_powmod2_preinv(lc, l0 - l2, mod.n, mod.ninv);
80 res = n_mulmod2_preinv(res, lc, mod.n, mod.ninv);
81
82 if (((l0 | l1) & 1) == 0)
83 {
84 res = nmod_neg(res, mod);
85 }
86 }
87 else
88 {
89 if (l1 == 1)
90 {
91 lc = n_powmod2_preinv(lc, l0 - 1, mod.n, mod.ninv);
92 res = n_mulmod2_preinv(res, lc, mod.n, mod.ninv);
93 }
94 else
95 {
96 res = 0;
97 }
98 }
99 }
100 while (l2 > 0);
101
102 _nmod_vec_clear(w);
103
104 return res;
105 }
106 }
107
108 mp_limb_t
nmod_poly_resultant_euclidean(const nmod_poly_t f,const nmod_poly_t g)109 nmod_poly_resultant_euclidean(const nmod_poly_t f, const nmod_poly_t g)
110 {
111 const slong len1 = f->length;
112 const slong len2 = g->length;
113 mp_limb_t r;
114
115 if (len1 == 0 || len2 == 0)
116 {
117 r = 0;
118 }
119 else
120 {
121 if (len1 >= len2)
122 {
123 r = _nmod_poly_resultant_euclidean(f->coeffs, len1,
124 g->coeffs, len2, f->mod);
125 }
126 else
127 {
128 r = _nmod_poly_resultant_euclidean(g->coeffs, len2,
129 f->coeffs, len1, f->mod);
130
131 if (((len1 | len2) & WORD(1)) == WORD(0))
132 r = nmod_neg(r, f->mod);
133 }
134 }
135
136 return r;
137 }
138
139