Add polynomial division

This commit is contained in:
Varmen8 2018-06-28 00:06:30 +02:00
parent 6454c537c2
commit 64b400ba77

78
main.py
View File

@ -47,7 +47,11 @@ class Poly:
else: else:
elements[degree] += coefficient % self.int_mod elements[degree] += coefficient % self.int_mod
return Poly(self.int_mod, list(reversed(list(elements.values())))) els = {}
for i in reversed(range(len(elements))):
els[f"x{i}"] = elements[f"x{i}"]
return Poly(self.int_mod, list(reversed(list(els.values()))))
def __mod__(self, other): def __mod__(self, other):
elements = {} elements = {}
@ -98,22 +102,34 @@ class Poly:
def __truediv__(self, other): def __truediv__(self, other):
if self.int_mod != other.int_mod: assert self.int_mod == other.int_mod
raise Exception("Different modulo")
if other.is_empty(): if other.is_empty():
raise ZeroDivisionError("Polynomial is empty") raise ZeroDivisionError("Polynomial is empty")
fdeg = len(self.elements) - 1 poly = Poly(self.int_mod, list(reversed(list(self.elements.values()))))
fdeg = len(poly.elements) - 1
sdeg = len(other.elements) - 1 sdeg = len(other.elements) - 1
while not other.is_empty(): while fdeg >= sdeg:
coefficient = self.elements[f"x{fdeg}"] / other.elements[f"x{sdeg}"] coefficient = poly.elements[f"x{fdeg}"] / other.elements[f"x{sdeg}"]
coefficient %= self.int_mod coefficient %= poly.int_mod
degree = fdeg - sdeg degree = fdeg - sdeg
# print(self.elements["x2"]) divpoly = [0 for x in range(degree + 1)]
# break divpoly[degree] = coefficient
divpoly = Poly(poly.int_mod, divpoly)
mulpoly = divpoly * other
poly -= mulpoly
for i in poly.elements.keys():
if poly.elements[f"{i}"] != 0:
fdeg = int(i[1:])
break
return poly
def is_empty(self): def is_empty(self):
@ -147,7 +163,13 @@ class PolyIntField:
if __name__ == "__main__": if __name__ == "__main__":
p = Poly(5, [-4, 0, -2, 1])
a = Poly(10, [-4, 0, -2, 1])
b = Poly(10, [-3, 1])
c = a/b
print(c)
# print(a - Poly(10, [0, 0, -3, 1]))
# p = Poly(5, [-4, 0, -2, 1])
# print(p) # print(p)
# c = p * p # c = p * p
# print(c.elements) # print(c.elements)
@ -158,29 +180,23 @@ if __name__ == "__main__":
# print(d) # print(d)
# print(p) # print(p)
# print(p + d) # print(p + d)
d = Poly(5, [-3, 1]) # d = Poly(5, [-3, 1])
g = Poly(5, [1, 2, 1]) # g = Poly(5, [1, 2, 1])
print(d) # print(d)
print(g) # print(g)
print() # print()
#
# # print(g)
# print(g - d)
# print(d - g)
#
# print() # print()
# print(g ** 2)
# print(d)
# print(g)
# # c = d * g
# print(g * d)
# print(d * g)
# print(g + d)
# print(d + g) # print(d + g)
# print(d) # print(g + d)
# print(g) #
print(g - d) # print()
print(d - g) # print(d * g)
# print(g * d)
print()
print(d + g)
print(g + d)
# print(d) # print(d)
# print(g) # print(g)
# print(g - d) # print(g - d)