Debian Codegraph @

texmf-dist/tex/lualatex/luacas/algebra/luacas-polynomialring.lua

raw
1 --- @class PolynomialRing
2 --- Represents an element of a polynomial ring.
3 --- @field coefficients table<number, Ring>
4 --- @field symbol SymbolExpression
5 --- @field ring RingIdentifier
6 PolynomialRing = {}
7 local __PolynomialRing = {}
8
9 -- Metatable for ring objects.
10 local __obj = {__index = PolynomialRing, __eq = function(a, b)
11 return a["ring"] == b["ring"] and
12 (a["child"] == b["child"] or a["child"] == nil or b["child"] == nil) and
13 (a["symbol"] == b["symbol"] or a["child"] == nil or b["child"] == nil)
14 end, __tostring = function(a)
15 if a.child and a.symbol then return tostring(a.child) .. "[" .. a.symbol .. "]" else return "(Generic Polynomial Ring)" end
16 end}
17
18 --------------------------
19 -- Static functionality --
20 --------------------------
21
22 --- Creates a new ring with the given symbol and child ring.
23 --- @param symbol SymbolExpression
24 --- @param child RingIdentifier
25 --- @return RingIdentifier
26 function PolynomialRing.makering(symbol, child)
27 local t = {ring = PolynomialRing}
28 t.symbol = symbol
29 t.child = child
30 t = setmetatable(t, __obj)
31 return t
32 end
33
34 -- Shorthand constructor for a polynomial ring with integer or integer mod ring coefficients.
35 function PolynomialRing.R(symbol, modulus)
36 if modulus then
37 return PolynomialRing.makering(symbol, IntegerModN.makering(modulus))
38 end
39 return PolynomialRing.makering(symbol, Integer.getring())
40 end
41
42 --- Returns the GCD of two polynomials in a ring, assuming both rings are euclidean domains.
43 --- @param a PolynomialRing
44 --- @param b PolynomialRing
45 --- @return PolynomialRing
46 function PolynomialRing.gcd(a, b)
47 if a.symbol ~= b.symbol then
48 error("Cannot take the gcd of two polynomials with different symbols")
49 end
50 while b ~= Integer.zero() do
51 a, b = b, a % b
52 end
53 return a // a:lc()
54 end
55
56 -- Returns the GCD of two polynomials in a ring, assuming both rings are euclidean domains.
57 -- Also returns bezouts coefficients via extended gcd.
58 --- @param a PolynomialRing
59 --- @param b PolynomialRing
60 --- @return PolynomialRing, PolynomialRing, PolynomialRing
61 function PolynomialRing.extendedgcd(a, b)
62 local oldr, r = a, b
63 local olds, s = Integer.one(), Integer.zero()
64 local oldt, t = Integer.zero(), Integer.one()
65 while r ~= Integer.zero() do
66 local q = oldr // r
67 oldr, r = r, oldr - q*r
68 olds, s = s, olds - q*s
69 oldt, t = t, oldt - q*t
70 end
71 return oldr // oldr:lc(), olds // oldr:lc(), oldt // oldr:lc()
72 end
73
74 -- Returns the resultant of two polynomials in the same ring, whose coefficients are all part of a field.
75 --- @param a PolynomialRing
76 --- @param b PolynomialRing
77 --- @return Field
78 function PolynomialRing.resultant(a, b)
79
80 if a.ring == PolynomialRing.getring() or b.ring == PolynomialRing.getring() then
81 return PolynomialRing.resultantmulti(a, b)
82 end
83
84 local m, n = a.degree, b.degree
85 if n == Integer.zero() then
86 return b.coefficients[0]^m
87 end
88
89 local r = a % b
90 if r == Integer.zero() then
91 return r.coefficients[0]
92 end
93
94 local s = r.degree
95 local l = b:lc()
96
97 return Integer(-1)^(m*n) * l^(m-s) * PolynomialRing.resultant(b, r)
98 end
99
100 -- Returns the resultant of two polynomials in the same ring, whose coefficients are not part of a field.
101 --- @param a PolynomialRing
102 --- @param b PolynomialRing
103 --- @return Ring
104 function PolynomialRing.resultantmulti(a, b)
105 local m, n = a.degree, b.degree
106
107 if m < n then
108 return Integer(-1) ^ (m * n) * PolynomialRing.resultantmulti(b, a)
109 end
110 if n == Integer.zero() then
111 return b.coefficients[0]^m
112 end
113
114 local delta = m - n + Integer(1)
115 local _ , r = PolynomialRing.pseudodivide(a, b)
116 if r == Integer.zero() then
117 return r.coefficients[0]
118 end
119
120 local s = r.degree
121 local w = Integer(-1)^(m*n) * PolynomialRing.resultant(b, r)
122 local l = b:lc()
123 local k = delta * n - m + s
124 local f = l ^ k
125 return w // f
126 end
127
128 -- Given two polynomials a and b, returns a list of the remainders generated by the monic Euclidean algorithm.
129 --- @param a PolynomialRing
130 --- @param b PolynomialRing
131 --- @return table<number, Ring>
132 function PolynomialRing.monicgcdremainders(a, b)
133 if a.symbol ~= b.symbol then
134 error("Cannot take the gcd of two polynomials with different symbols")
135 end
136
137 local remainders = {a / a:lc(), b / b:lc()}
138 while true do
139 local q = remainders[#remainders - 1] // remainders[#remainders]
140 local c = remainders[#remainders - 1] - q*remainders[#remainders]
141 if c ~= Integer.zero() then
142 remainders[#remainders+1] = c/c:lc()
143 else
144 break
145 end
146 end
147
148 return remainders
149 end
150
151 -- Returns the partial fraction decomposition of the rational function g/f
152 -- given g, f, and some (not nessecarily irreducible) factorization of f.
153 -- If the factorization is omitted, the irreducible factorization is used.
154 -- The degree of g must be less than the degree of f.
155 --- @param g PolynomialRing
156 --- @param f PolynomialRing
157 --- @param ffactors Expression
158 --- @return Expression
159 function PolynomialRing.partialfractions(g, f, ffactors)
160
161 if g.degree >= f.degree then
162 error("Argument Error: The degree of g must be less than the degree of f.")
163 end
164
165 -- Converts f to a monic polynomial.
166 g = g * f:lc()
167 f = f / f:lc()
168
169 ffactors = ffactors or f:factor()
170
171 local expansionterms = {}
172
173 for _, factor in ipairs(ffactors.expressions) do
174 local k
175 local m
176 if factor.getring and factor:getring() == PolynomialRing:getring() then
177 m = factor
178 k = Integer.one()
179 elseif not factor:isconstant() then
180 m = factor.expressions[1]
181 k = factor.expressions[2]
182 end
183
184 if not factor:isconstant() then
185 -- Uses Chinese Remainder Theorem for each factor to determine the numerator of the term in the decomposition
186 local mk = m^k
187 local v = g % mk
188 local _, minv, _ = PolynomialRing.extendedgcd(f // mk, mk)
189 local c = v*minv % mk
190
191
192 if k == Integer.one() then
193 expansionterms[#expansionterms+1] = BinaryOperation.ADDEXP({BinaryOperation.DIVEXP({c, BinaryOperation.POWEXP({m, Integer.one()})})})
194 else
195 -- Uses the p-adic expansion of c to split terms with repeated roots.
196 local q = c
197 local r
198 local innerterms = {}
199 for i = k:asnumber(), 1, -1 do
200 q, r = q:divremainder(m)
201 innerterms[#innerterms+1] = BinaryOperation.DIVEXP({r, BinaryOperation.POWEXP({m, Integer(i)})})
202 end
203 expansionterms[#expansionterms+1] = BinaryOperation.ADDEXP(innerterms)
204 end
205 end
206 end
207
208 return BinaryOperation.ADDEXP(expansionterms)
209
210 end
211
212 ----------------------------
213 -- Instance functionality --
214 ----------------------------
215
216 -- So we don't have to copy the Euclidean operations each time
217 __PolynomialOperations = Copy(__EuclideanOperations)
218 __PolynomialOperations.__index = PolynomialRing
219 __PolynomialOperations.__tostring = function(a)
220 local out = ""
221 local loc = a.degree:asnumber()
222 while loc >= 0 do
223 if a.ring == PolynomialRing.getring() or (a.ring == Rational.getring() and a.ring.symbol) then
224 out = out .. "(" .. tostring(a.coefficients[loc]) .. ")" .. a.symbol .. "^" .. tostring(math.floor(loc)) .. "+"
225 else
226 out = out .. tostring(a.coefficients[loc]) .. a.symbol .. "^" .. tostring(math.floor(loc)) .. "+"
227 end
228 loc = loc - 1
229 end
230 return string.sub(out, 1, string.len(out) - 1)
231 end
232 __PolynomialOperations.__div = function(a, b)
233 if not b.getring then
234 return BinaryOperation.DIVEXP({a, b})
235 end
236 if Ring.resultantring(a.ring, b:getring()) ~= Ring.resultantring(a:getring(), b:getring()) then
237 return a:div(b:inring(Ring.resultantring(a:getring(), b:getring())))
238 end
239 if b.ring and b:getring() == Rational:getring() and a.symbol == b.ring.symbol then
240 return a:inring(Ring.resultantring(a:getring(), b:getring())):div(b)
241 end
242 if a:getring() == b:getring() then
243 return Rational(a, b, true)
244 end
245 -- TODO: Fix this for arbitrary depth
246 if a:getring() == PolynomialRing:getring() and b:getring() == PolynomialRing:getring() and a.symbol == b.symbol then
247 local oring = Ring.resultantring(a:getring(), b:getring())
248 return Rational(a:inring(oring), b:inring(oring), true)
249 end
250 return BinaryOperation.DIVEXP({a, b})
251 end
252
253 function PolynomialRing:tolatex()
254 local out = ''
255 local loc = self.degree:asnumber()
256 if loc == 0 then
257 return self.coefficients[loc]:tolatex()
258 end
259 if self.ring == Rational.getring() or self.ring == Integer.getring() or self.ring == IntegerModN.getring() then
260 if self.coefficients[loc] ~= Integer.one() then
261 if self.coefficients[loc] == Integer(-1) then
262 out = out .. "-" .. self.symbol
263 elseif self.coefficients[loc] == Integer.zero() then
264 goto lead
265 else
266 out = out .. self.coefficients[loc]:tolatex() .. self.symbol
267 end
268 else
269 out = out .. self.symbol
270 end
271 if loc ~=1 then
272 out = out .. "^{" .. loc .. "}"
273 end
274 ::lead::
275 loc = loc -1
276 while loc >=0 do
277 local coeff = self.coefficients[loc]
278 if coeff == Integer.one() then
279 if loc == 0 then
280 out = out .. "+" .. coeff:tolatex()
281 goto skip
282 else
283 out = out .. "+"
284 goto continue
285 end
286 end
287 if coeff == Integer(-1) then
288 if loc == 0 then
289 out = out .. "-" .. coeff:neg():tolatex()
290 goto skip
291 else
292 out = out .. "-"
293 goto continue
294 end
295 end
296 if coeff < Integer.zero() then
297 out = out .. "-" .. coeff:neg():tolatex()
298 end
299 if coeff == Integer.zero() then
300 goto skip
301 end
302 if coeff > Integer.zero() then
303 out = out .. "+" .. coeff:tolatex()
304 end
305 ::continue::
306 if loc > 1 then
307 out = out .. self.symbol .. "^{" .. loc .. "}"
308 end
309 if loc == 1 then
310 out = out .. self.symbol
311 end
312 ::skip::
313 loc = loc-1
314 end
315 else
316 while loc >=0 do
317 if loc >=1 then
318 out = out .. self.coefficients[loc]:tolatex() .. self.symbol .. "^{" .. loc .. "} + "
319 else
320 out = out .. self.coefficients[loc]:tolatex() .. self.symbol .. "^{" .. loc .. "}"
321 end
322 loc = loc-1
323 end
324 end
325 return out
326 end
327
328 function PolynomialRing:isatomic()
329 --if self.degree >= Integer.one() then
330 -- return false
331 --else
332 return false
333 --end
334 end
335 --test
336
337 -- Creates a new polynomial ring given an array of coefficients and a symbol
338 function PolynomialRing:new(coefficients, symbol, degree)
339 local o = {}
340 o = setmetatable(o, __PolynomialOperations)
341
342 if type(coefficients) ~= "table" then
343 error("Sent parameter of wrong type: Coefficients must be in an array")
344 end
345 o.coefficients = {}
346 o.degree = degree or Integer(-1)
347
348 if type(symbol) ~= "string" and not symbol.symbol then
349 error("Symbol must be a string")
350 end
351 o.symbol = symbol.symbol or symbol
352
353 -- Determines what ring the polynomial ring should have as its child
354 for index, coefficient in pairs(coefficients) do
355 if type(index) ~= "number" then
356 error("Sent parameter of wrong type: Coefficients must be in an array")
357 end
358 if not coefficient.getring then
359 error("Sent parameter of wrong type: Coefficients must be elements of a ring")
360 end
361 if not o.ring then
362 o.ring = coefficient:getring()
363 else
364 local newring = coefficient:getring()
365 local combinedring = Ring.resultantring(o.ring, newring)
366 if combinedring == newring then
367 o.ring = newring
368 elseif not o.ring == combinedring then
369 error("Sent parameter of wrong type: Coefficients must all be part of the same ring")
370 end
371 end
372 end
373
374 if not coefficients[0] then
375 -- Constructs the coefficients when a new polynomial is instantiated as an array
376 for index, coefficient in ipairs(coefficients) do
377 o.coefficients[index - 1] = coefficient
378 o.degree = o.degree + Integer.one()
379 end
380 else
381 -- Constructs the coefficients from an existing polynomial of coefficients
382 local loc = o.degree:asnumber()
383 while loc > 0 do
384 if not coefficients[loc] or coefficients[loc] == coefficients[loc]:zero() then
385 o.degree = o.degree - Integer.one()
386 else
387 break
388 end
389 loc = loc - 1
390 end
391
392 while loc >= 0 do
393 o.coefficients[loc] = coefficients[loc]
394 loc = loc - 1
395 end
396 end
397
398 -- Each value of the polynomial greater than its degree is implicitly zero
399 o.coefficients = setmetatable(o.coefficients, {__index = function (table, key)
400 return o:zeroc()
401 end})
402 return o
403 end
404
405 -- Returns the ring this object is an element of
406 function PolynomialRing:getring()
407 local t = {ring = PolynomialRing}
408 if self then
409 t.child = self.ring
410 t.symbol = self.symbol
411 end
412 t = setmetatable(t, __obj)
413 return t
414 end
415
416 -- Explicitly converts this element to an element of another ring
417 function PolynomialRing:inring(ring)
418
419 -- Faster equality check
420 if ring == self:getring() then
421 return self
422 end
423
424 if ring == Rational:getring() and ring.symbol then
425 return Rational(self:inring(ring.child), self:inring(ring.child):one(), true)
426 end
427
428 if ring.symbol == self.symbol then
429 local out = {}
430 for i = 0, self.degree:asnumber() do
431 out[i + 1] = self.coefficients[i]:inring(ring.child)
432 end
433 return PolynomialRing(out, self.symbol)
434 end
435
436 -- TODO: Allow re-ordering of polynomial rings, so from R[x][y] -> R[y][x] for instance
437 if ring == PolynomialRing:getring() then
438 return PolynomialRing({self:inring(ring.child)}, ring.symbol)
439 end
440
441 error("Unable to convert element to proper ring.")
442 end
443
444
445 -- Returns whether the ring is commutative
446 function PolynomialRing:iscommutative()
447 return true
448 end
449
450 function PolynomialRing:add(b)
451 local larger
452
453 if self.degree > b.degree then
454 larger = self
455 else
456 larger = b
457 end
458
459 local new = {}
460 local loc = 0
461 while loc <= larger.degree:asnumber() do
462 new[loc] = self.coefficients[loc] + b.coefficients[loc]
463 loc = loc + 1
464 end
465
466 return PolynomialRing(new, self.symbol, larger.degree)
467 end
468
469 function PolynomialRing:neg()
470 local new = {}
471 local loc = 0
472 while loc <= self.degree:asnumber() do
473 new[loc] = -self.coefficients[loc]
474 loc = loc + 1
475 end
476 return PolynomialRing(new, self.symbol, self.degree)
477 end
478
479 function PolynomialRing:mul(b)
480 -- Grade-school multiplication is actually faster up to a very large polynomial size due to Lua's overhead.
481 local new = {}
482
483 local sd = self.degree:asnumber()
484 local bd = b.degree:asnumber()
485
486 for i = 0, sd+bd do
487 new[i] = self:zeroc()
488 for j = math.max(0, i-bd), math.min(sd, i) do
489 new[i] = new[i] + self.coefficients[j]*b.coefficients[i-j]
490 end
491 end
492 return PolynomialRing(new, self.symbol, self.degree + b.degree)
493 -- return PolynomialRing(PolynomialRing.mul_rec(self.coefficients, b.coefficients), self.symbol, self.degree + b.degree)
494 end
495
496 -- Performs Karatsuba multiplication without constructing new polynomials recursively
497 function PolynomialRing.mul_rec(a, b)
498 if #a==0 and #b==0 then
499 return {[0]=a[0] * b[0], [1]=Integer.zero()}
500 end
501
502 local k = Integer.ceillog(Integer.max(Integer(#a), Integer(#b)) + Integer.one(), Integer(2))
503 local n = Integer(2) ^ k
504 local m = n / Integer(2)
505 local nn = n:asnumber()
506 local mn = m:asnumber()
507
508 local a0, a1, b0, b1 = {}, {}, {}, {}
509
510 for e = 0, mn - 1 do
511 a0[e] = a[e] or Integer.zero()
512 a1[e] = a[e + mn] or Integer.zero()
513 b0[e] = b[e] or Integer.zero()
514 b1[e] = b[e + mn] or Integer.zero()
515 end
516
517 local p1 = PolynomialRing.mul_rec(a1, b1)
518 local p2a = Copy(a0)
519 local p2b = Copy(b0)
520 for e = 0, mn - 1 do
521 p2a[e] = p2a[e] + a1[e]
522 p2b[e] = p2b[e] + b1[e]
523 end
524 local p2 = PolynomialRing.mul_rec(p2a, p2b)
525 local p3 = PolynomialRing.mul_rec(a0, b0)
526 local r = {}
527 for e = 0, mn - 1 do
528 p2[e] = p2[e] - p1[e] - p3[e]
529 r[e] = p3[e]
530 r[e + mn] = p2[e]
531 r[e + nn] = p1[e]
532 end
533 for e = mn, nn - 1 do
534 p2[e] = p2[e] - p1[e] - p3[e]
535 r[e] = r[e] + p3[e]
536 r[e + mn] = r[e + mn] + p2[e]
537 r[e + nn] = p1[e]
538 end
539
540 return r
541 end
542
543 -- Uses synthetic division.
544 function PolynomialRing:divremainder(b)
545 local n, m = self.degree:asnumber(), b.degree:asnumber()
546
547 if m > n then
548 return self:zero(), self
549 end
550
551 local o = Copy(self.coefficients)
552 local lc = b:lc()
553 for i = n, m, -1 do
554 o[i] = o[i] / lc
555
556 if o[i] ~= self:zeroc() then
557 for j = 1, m do
558 o[i-j] = o[i-j] - b.coefficients[m - j] * o[i]
559 end
560 end
561 end
562
563 local q = {}
564 local r = {}
565 for i = 0, m-1 do
566 r[i] = o[i]
567 end
568
569 r[0] = r[0] or self:zeroc()
570
571 for i = m, #o do
572 q[i - m] = o[i]
573 end
574
575 return PolynomialRing(q, self.symbol, self.degree), PolynomialRing(r, self.symbol, Integer.max(Integer.zero(), b.degree-Integer.one()))
576 end
577
578 -- Performs polynomial pseudodivision of this polynomial by another in the same ring,
579 -- and returns both the pseudoquotient and pseudoremainder.
580 -- In the case where both coefficients are fields, this is equivalent to division with remainder.
581 function PolynomialRing:pseudodivide(b)
582
583 local p = self:zero()
584 local s = self
585 local m = s.degree
586 local n = b.degree
587 local delta = Integer.max(m - n + Integer.one(), Integer.zero())
588
589 local lcb = b:lc()
590 local sigma = Integer.zero()
591
592 while m >= n and s ~= Integer.zero() do
593 local lcs = s:lc()
594 p = p * lcb + self:one():multiplyDegree((m-n):asnumber()) * lcs
595 s = s * lcb - b * self:one():multiplyDegree((m-n):asnumber()) * lcs
596 sigma = sigma + Integer.one()
597 m = s.degree
598 end
599
600 if delta - sigma == Integer.zero() then
601 return p,s
602 else
603 return lcb^(delta - sigma) * p, lcb^(delta - sigma) * s
604 end
605 end
606
607 -- Polynomial rings are never fields, but when dividing by a polynomial by a constant we may want to use / instead of //
608 function PolynomialRing:div(b)
609 return self:divremainder(b)
610 end
611
612 function PolynomialRing:zero()
613 return self.coefficients[0]:zero():inring(self:getring())
614 end
615
616 function PolynomialRing:zeroc()
617 return self.coefficients[0]:zero()
618 end
619
620 function PolynomialRing:one()
621 return self.coefficients[0]:one():inring(self:getring())
622 end
623
624 function PolynomialRing:onec()
625 return self.coefficients[0]:one()
626 end
627
628 function PolynomialRing:eq(b)
629 for i=0,math.max(self.degree:asnumber(), b.degree:asnumber()) do
630 if self.coefficients[i] ~= b.coefficients[i] then
631 return false
632 end
633 end
634 return true
635 end
636
637 -- Returns the leading coefficient of this polynomial
638 function PolynomialRing:lc()
639 return self.coefficients[self.degree:asnumber()]
640 end
641
642 --- @return boolean
643 function PolynomialRing:isconstant()
644 return false
645 end
646
647 -- This expression is free of a symbol if and only if the symbol is not the symbol used to create the ring.
648 function PolynomialRing:freeof(symbol)
649 return symbol.symbol ~= self.symbol
650 end
651
652 -- Replaces each expression in the map with its value.
653 function PolynomialRing:substitute(map)
654 return self:tocompoundexpression():substitute(map)
655 end
656
657 -- Expands a polynomial expression. Polynomials are already in expanded form, so we just need to autosimplify.
658 function PolynomialRing:expand()
659 return self:tocompoundexpression():autosimplify()
660 end
661
662 function PolynomialRing:autosimplify()
663 return self:tocompoundexpression():autosimplify()
664 end
665
666 -- Transforms from array format to an expression format.
667 function PolynomialRing:tocompoundexpression()
668 local terms = {}
669 for exponent, coefficient in pairs(self.coefficients) do
670 terms[exponent + 1] = BinaryOperation(BinaryOperation.MUL, {coefficient:tocompoundexpression(),
671 BinaryOperation(BinaryOperation.POW, {SymbolExpression(self.symbol), Integer(exponent)})})
672 end
673 return BinaryOperation(BinaryOperation.ADD, terms)
674 end
675
676 -- Uses Horner's rule to evaluate a polynomial at a point
677 function PolynomialRing:evaluateat(x)
678 local out = self:zeroc()
679 for i = self.degree:asnumber(), 1, -1 do
680 out = out + self.coefficients[i]
681 out = out * x
682 end
683 return out + self.coefficients[0]
684 end
685
686 -- Multiplies this polynomial by x^n
687 function PolynomialRing:multiplyDegree(n)
688 local new = {}
689 for e = 0, n-1 do
690 new[e] = self:zeroc()
691 end
692 local loc = n
693 while loc <= self.degree:asnumber() + n do
694 new[loc] = self.coefficients[loc - n]
695 loc = loc + 1
696 end
697 return PolynomialRing(new, self.symbol, self.degree + Integer(n))
698 end
699
700 -- Returns the formal derivative of this polynomial
701 function PolynomialRing:derivative()
702 if self.degree == Integer.zero() then
703 return PolynomialRing({self:zeroc()}, self.symbol, Integer(-1))
704 end
705 local new = {}
706 for e = 1, self.degree:asnumber() do
707 new[e - 1] = Integer(e) * self.coefficients[e]
708 end
709 return PolynomialRing(new, self.symbol, self.degree - Integer.one())
710 end
711
712 -- Returns the square-free factorization of a polynomial
713 function PolynomialRing:squarefreefactorization()
714 local terms
715 if self.ring == Rational.getring() or self.ring == Integer.getring() then
716 terms = self:rationalsquarefreefactorization()
717 elseif self.ring == IntegerModN.getring() then
718 if not self.ring.modulus:isprime() then
719 error("Cannot compute a square-free factorization of a polynomial ring contructed from a ring that is not a field.")
720 end
721 terms = self:modularsquarefreefactorization()
722 end
723
724 local expressions = {self:lc()}
725 local j = 1
726 for index, term in ipairs(terms) do
727 if term.degree ~= Integer.zero() or term.coefficients[0] ~= Integer.one() then
728 j = j + 1
729 expressions[j] = BinaryOperation.POWEXP({term, Integer(index)})
730 end
731 end
732
733 return BinaryOperation.MULEXP(expressions)
734 end
735
736 -- Factors a polynomial into irreducible terms
737 function PolynomialRing:factor()
738 -- Square-free factorization over an integral domain (so a polynomial ring constructed from a field)
739 local squarefree = self:squarefreefactorization()
740 local squarefreeterms = {}
741 local result = {squarefree.expressions[1]}
742 for i, expression in ipairs(squarefree.expressions) do
743 if i > 1 then
744 -- Converts square-free polynomials with rational coefficients to integer coefficients so Rational Roots / Zassenhaus can factor them
745 if expression.expressions[1].ring == Rational.getring() then
746 local factor, integerpoly = expression.expressions[1]:rationaltointeger()
747 result[1] = result[1] * factor ^ expression.expressions[2]
748 squarefreeterms[i - 1] = integerpoly
749 else
750 squarefreeterms[i - 1] = expression.expressions[1]
751 end
752 end
753 end
754
755 for i, expression in ipairs(squarefreeterms) do
756 local terms
757 if expression.ring == Integer.getring() then
758 -- Factoring over the integers first uses the rational roots test to factor out monomials (for efficiency purposes)
759 local remaining, factors = expression:rationalroots()
760 terms = factors
761 -- Then applies the Zassenhaus algorithm if there entire polynomial has not been factored into monomials
762 if remaining ~= Integer.one() then
763 remaining = remaining:zassenhausfactor()
764 for _, exp in ipairs(remaining) do
765 terms[#terms+1] = exp
766 end
767 end
768 end
769 if expression.ring == IntegerModN.getring() then
770 -- Berlekamp factorization is used for rings with integers mod a prime as coefficients
771 terms = expression:berlekampfactor()
772 end
773 for _, factor in ipairs(terms) do
774 result[#result+1] = BinaryOperation.POWEXP({factor, squarefree.expressions[i + 1].expressions[2]})
775 end
776 end
777 return BinaryOperation.MULEXP(result)
778 end
779
780 -- Uses the Rational Root test to factor out monomials of a square-free polynomial.
781 function PolynomialRing:rationalroots()
782 local remaining = self
783 local roots = {}
784 if self.coefficients[0] == Integer.zero() then
785 roots[1] = PolynomialRing({Integer.zero(), Integer.one()}, self.symbol)
786 remaining = remaining // roots[1]
787 end
788 -- This can be slower than Zassenhaus if the digits are large enough, since factoring integers is slow
789 -- if self.coefficients[0] > Integer(Integer.DIGITSIZE - 1) or self:lc() > Integer(Integer.DIGITSIZE - 1) then
790 -- return remaining, roots
791 -- end
792 while remaining ~= Integer.one() do
793 :: nextfactor ::
794 local a = remaining.coefficients[0]
795 local b = remaining:lc()
796 local afactors = a:divisors()
797 local bfactors = b:divisors()
798 for _, af in ipairs(afactors) do
799 for _, bf in ipairs(bfactors) do
800 local testroot = Rational(af, bf, true)
801 if remaining:evaluateat(testroot) == Integer.zero() then
802 roots[#roots+1] = PolynomialRing({-testroot.numerator, testroot.denominator}, self.symbol)
803 remaining = remaining // roots[#roots]
804 goto nextfactor
805 end
806 if remaining:evaluateat(-testroot) == Integer.zero() then
807 roots[#roots+1] = PolynomialRing({testroot.numerator, testroot.denominator}, self.symbol)
808 remaining = remaining // roots[#roots]
809 goto nextfactor
810 end
811 end
812 end
813 break
814 end
815
816 return remaining, roots
817 end
818
819 -- Returns a list of roots of the polynomial, simplified up to cubics.
820 function PolynomialRing:roots()
821 local roots = {}
822 local factorization = self:factor()
823
824 for i, factor in ipairs(factorization.expressions) do
825 if i > 1 then
826 local decomp = factor.expressions[1]:decompose()
827 for _, poly in ipairs(decomp) do
828 if poly.degree > Integer(3) then
829 table.insert(roots,RootExpression(factor.expressions[1]))
830 goto nextfactor
831 end
832 end
833 local factorroots = RootExpression(decomp[#decomp]):autosimplify()
834 if factorroots == true then
835 return true
836 end
837 if factorroots == false then
838 goto nextfactor
839 end
840 local replaceroots = {}
841 for j = #decomp - 1,1,-1 do
842 for _, root in ipairs(factorroots) do
843 local temp = RootExpression(decomp[j]):autosimplify(root)
844 if temp == true then
845 return true
846 end
847 if factorroots == false then
848 goto nextfactor
849 end
850 replaceroots = JoinArrays(replaceroots, temp)
851 end
852 factorroots = replaceroots
853 end
854 roots = JoinArrays(roots, factorroots)
855 end
856 end
857 ::nextfactor::
858 return roots
859 end
860
861 -----------------
862 -- Inheritance --
863 -----------------
864
865 __PolynomialRing.__index = Ring
866 __PolynomialRing.__call = PolynomialRing.new
867 PolynomialRing = setmetatable(PolynomialRing, __PolynomialRing)