Zadanie 3 - CRC #27

Closed
s426284 wants to merge 10 commits from s426284/DALGLI0:zad3 into master
Showing only changes of commit 448979c654 - Show all commits

87
wielomiany.py Normal file
View File

@ -0,0 +1,87 @@
class Polynomial:
n = 0
def __init__(self, *args):
self.degree = len(args) - 1
self.coefficients = list(args)
@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(n) for x in result]
return Polynomial(*result)
@staticmethod
def divide(p1, p2):
def inverse(x):
for i in range(1, int(n)):
r = (i * x) % int(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 i 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(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))
n = input("Enter n: ")
Polynomial.n = int(n)
c1 = [int(x) for x in input("Enter 1st polynomial (coefficients divided by space): ").split()]
c1 = [x % Polynomial.n for x in c1]
c2 = [int(x) for x in input("Enter 2nd polynomial: ").split()]
c2 = [x % Polynomial.n for x in c2]
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)