forked from kalmar/DALGLI0
107 lines
2.7 KiB
Python
107 lines
2.7 KiB
Python
import sys
|
|
import ast
|
|
|
|
class Polynomial:
|
|
|
|
n = 0
|
|
|
|
def __init__(self, coef_list):
|
|
self.degree = len(coef_list) - 1
|
|
self.coefficients = coef_list
|
|
|
|
@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)
|
|
|
|
@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]
|
|
result = [x % int(Polynomial.n) for x in result]
|
|
return Polynomial(result)
|
|
|
|
@staticmethod
|
|
def divide(p1, p2):
|
|
def inverse(x):
|
|
for i in range(1, int(Polynomial.n)):
|
|
r = (i * x) % int(Polynomial.n)
|
|
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 = []
|
|
for _ in range(tmp_exp):
|
|
tmp.append(0)
|
|
tmp.append(tmp_coef)
|
|
tmp_poly = Polynomial(tmp)
|
|
sub = Polynomial.multiply(p2, tmp_poly)
|
|
f = [x - y for x, y in zip(f, sub.coefficients)]
|
|
f = [x % int(Polynomial.n) for x in f]
|
|
while f and f[-1] == 0:
|
|
f.pop()
|
|
return Polynomial(f)
|
|
|
|
@staticmethod
|
|
def gcd(p1, p2):
|
|
if len(p2.coefficients) == 0:
|
|
return p1
|
|
return Polynomial.gcd(p2, Polynomial.divide(p1, p2))
|
|
|
|
|
|
def main():
|
|
Polynomial.n = int(sys.argv[1])
|
|
c1 = ast.literal_eval(sys.argv[2])
|
|
c2 = ast.literal_eval(sys.argv[3])
|
|
|
|
f = Polynomial(c1)
|
|
g = Polynomial(c2)
|
|
|
|
ans = []
|
|
|
|
mul = Polynomial.multiply(f, g)
|
|
ans.append(mul.coefficients)
|
|
|
|
try:
|
|
div = Polynomial.divide(f, g)
|
|
ans.append(div.coefficients)
|
|
except ZeroDivisionError as e:
|
|
ans.append(e)
|
|
|
|
try:
|
|
gcd = Polynomial.gcd(f, g)
|
|
ans.append(gcd.coefficients)
|
|
except ZeroDivisionError as e:
|
|
ans.append(e)
|
|
|
|
print(ans)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|