Created
September 26, 2020 06:07
-
-
Save SoftPoison/2ee1ee1aa38db54e0085eb4acc0a2526 to your computer and use it in GitHub Desktop.
Computes the product of two polynomials (modulo another polynomial) in a given finite field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod = lambda x, n: x % n if x >= 0 else mod(x+n, n) | |
vmod = lambda v, n: [mod(e, n) for e in v] | |
def multip(u, v, p): | |
w = [0] * (len(u)+len(v)-1) | |
for i, x in enumerate(u): | |
for j, y in enumerate(v): | |
w[i+j] += x*y | |
return vmod(w, p) | |
# computes u*v (mod f) in F_p[x] | |
# u, v, f: polynomials as arrays, i.e [3,0,2] = 3x^2 + 0x + 2 | |
# p: size of the finite field | |
def multip_modulo(u, v, f, p): | |
w = multip(u, v, p) | |
if len(w) < len(f): | |
return w | |
for i, e in enumerate(w): | |
g = [(e // f[0]) * x for x in f] | |
w = [mod(w[i] - g[i], p) for i in range(len(w))] | |
w = w[[0 if x == 0 else 1 for x in w].index(1):] | |
if len(w) < len(f): | |
return w | |
return w |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment