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
/*
Copyright (C) 2010 Sebastian Pancratz
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include "fmpz.h"
#include "fmpz_vec.h"
#include "fmpz_poly.h"
#include "fmpq_poly.h"
void _fmpq_poly_rem(fmpz * R, fmpz_t r,
const fmpz * A, const fmpz_t a, slong lenA,
const fmpz * B, const fmpz_t FLINT_UNUSED(b), slong lenB, const fmpz_preinvn_t inv)
{
slong lenR;
ulong d;
const fmpz * lead = B + (lenB - 1);
if (lenB == 1)
{
fmpz_one(r);
return;
}
/*
From pseudo division over Z we have
lead^d * A = Q * B + R
and thus
{A, a} = {b * Q, a * lead^d} * {B, b} + {R, a * lead^d}.
*/
_fmpz_poly_pseudo_rem(R, &d, A, lenA, B, lenB, inv);
/* Determine the actual length of R */
for (lenR = lenB - 2; lenR >= 0 && !R[lenR]; lenR--) ;
lenR++;
/* 1. lead^d == +-1. {R, r} = {R, a} up to sign */
if (d == UWORD(0) || *lead == WORD(1) || *lead == WORD(-1))
{
fmpz_one(r);
if (lenR > 0)
_fmpq_poly_scalar_div_fmpz(R, r, R, r, lenR, a);
if (*lead == WORD(-1) && d % UWORD(2))
_fmpz_vec_neg(R, R, lenR);
}
/* 2. lead^d != +-1. {R, r} = {R, a lead^d} */
else
{
/*
TODO: Improve this. Clearly we do not need to compute
den = a lead^d in many cases, but can determine the GCD from
lead alone already.
*/
fmpz_t den;
fmpz_init(den);
fmpz_pow_ui(den, lead, d);
fmpz_mul(den, a, den);
fmpz_one(r);
if (lenR > 0)
_fmpq_poly_scalar_div_fmpz(R, r, R, r, lenR, den);
fmpz_clear(den);
}
}
void fmpq_poly_rem(fmpq_poly_t R,
const fmpq_poly_t poly1, const fmpq_poly_t poly2)
{
slong lenA, lenB, lenR;
if (fmpq_poly_is_zero(poly2))
{
flint_throw(FLINT_DIVZERO, "Exception (fmpq_poly_rem). Division by zero.\n");
}
if (poly1->length < poly2->length)
{
fmpq_poly_set(R, poly1);
return;
}
/* Deal with aliasing */
if (R == poly1 || R == poly2)
{
fmpq_poly_t tempR;
fmpq_poly_init(tempR);
fmpq_poly_rem(tempR, poly1, poly2);
fmpq_poly_swap(R, tempR);
fmpq_poly_clear(tempR);
return;
}
lenA = poly1->length;
lenB = poly2->length;
lenR = lenB - 1;
fmpq_poly_fit_length(R, lenA); /* XXX: Need at least that much space */
_fmpq_poly_rem(R->coeffs, R->den,
poly1->coeffs, poly1->den, poly1->length,
poly2->coeffs, poly2->den, poly2->length, NULL);
_fmpq_poly_set_length(R, lenR);
_fmpq_poly_normalise(R);
}