2018-06-07 10:06:57 +02:00
|
|
|
import sys
|
|
|
|
import ast
|
|
|
|
|
2018-06-07 01:25:32 +02:00
|
|
|
class Polynomial:
|
|
|
|
|
|
|
|
n = 0
|
|
|
|
|
2018-06-07 10:06:57 +02:00
|
|
|
def __init__(self, coef_list):
|
|
|
|
self.degree = len(coef_list) - 1
|
2018-06-27 21:59:00 +02:00
|
|
|
self.coefficients = [x % Polynomial.n for x in coef_list]
|
2018-06-07 01:25:32 +02:00
|
|
|
|
2018-06-27 19:29:48 +02:00
|
|
|
@staticmethod
|
|
|
|
def add(p1, p2):
|
|
|
|
result = []
|
|
|
|
f = p1.coefficients
|
|
|
|
g = p2.coefficients
|
|
|
|
if len(f) >= len(g):
|
|
|
|
result = f
|
|
|
|
for i in range(0, len(g)):
|
|
|
|
result[i] = f[i] + g[i]
|
|
|
|
else:
|
|
|
|
result = g
|
|
|
|
for i in range(0, len(f)):
|
|
|
|
result[i] = f[i] + g[i]
|
|
|
|
result = [x % int(Polynomial.n) for x in result]
|
|
|
|
return Polynomial(result)
|
|
|
|
|
2018-06-07 01:25:32 +02:00
|
|
|
@staticmethod
|
|
|
|
def multiply(p1, p2):
|
|
|
|
result = [0] * (p1.degree + p2.degree + 1)
|
|
|
|
f = p1.coefficients
|
|
|
|
g = p2.coefficients
|
|
|
|
for i in range(0, len(f)):
|
|
|
|
for j in range(0, len(g)):
|
|
|
|
result[i+j] += f[i] * g[j]
|
2018-06-27 19:29:48 +02:00
|
|
|
result = [x % int(Polynomial.n) for x in result]
|
2018-06-07 10:06:57 +02:00
|
|
|
return Polynomial(result)
|
2018-06-07 01:25:32 +02:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def divide(p1, p2):
|
|
|
|
def inverse(x):
|
2018-06-27 19:29:48 +02:00
|
|
|
for i in range(1, int(Polynomial.n)):
|
|
|
|
r = (i * x) % int(Polynomial.n)
|
2018-06-07 01:25:32 +02:00
|
|
|
if r == 1:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise ZeroDivisionError
|
|
|
|
return i
|
|
|
|
if p1.degree < p2.degree:
|
|
|
|
return p1
|
|
|
|
f = p1.coefficients
|
|
|
|
g = p2.coefficients
|
|
|
|
g_lead_coef = g[-1]
|
|
|
|
g_deg = p2.degree
|
|
|
|
while len(f) >= len(g):
|
|
|
|
f_lead_coef = f[-1]
|
|
|
|
tmp_coef = f_lead_coef * inverse(g_lead_coef)
|
|
|
|
tmp_exp = len(f) - 1 - g_deg
|
|
|
|
tmp = []
|
2018-06-27 19:29:48 +02:00
|
|
|
for _ in range(tmp_exp):
|
2018-06-07 01:25:32 +02:00
|
|
|
tmp.append(0)
|
|
|
|
tmp.append(tmp_coef)
|
2018-06-07 10:06:57 +02:00
|
|
|
tmp_poly = Polynomial(tmp)
|
2018-06-07 01:25:32 +02:00
|
|
|
sub = Polynomial.multiply(p2, tmp_poly)
|
|
|
|
f = [x - y for x, y in zip(f, sub.coefficients)]
|
2018-06-27 19:29:48 +02:00
|
|
|
f = [x % int(Polynomial.n) for x in f]
|
2018-06-07 01:25:32 +02:00
|
|
|
while f and f[-1] == 0:
|
|
|
|
f.pop()
|
2018-06-07 10:06:57 +02:00
|
|
|
return Polynomial(f)
|
2018-06-07 01:25:32 +02:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def gcd(p1, p2):
|
|
|
|
if len(p2.coefficients) == 0:
|
|
|
|
return p1
|
2018-06-27 21:59:00 +02:00
|
|
|
return Polynomial.gcd(p2, Polynomial.divide(p1, p2))
|