2

Can anyone tell me how to find the inverse of a given polynomial using python programming? Ex: input given is to find the inverse of (x^2 + 1) modulo (x^4 + x + 1). the output should be : (x^3 + x + 1).

kelalaka
  • 48,443
  • 11
  • 116
  • 196

2 Answers2

1

To compute the invert of $P$ modulo $Q$ with $Q$ of degree $n+1$, an easy solution could be to solve a linear system with unknown: $\lambda_0, \dots, \lambda_n$ such that $P^{-1}= \sum \lambda_i X^i$.

Then we know $(P \cdot(\sum \lambda_i X^i) )\mod Q = 1$. And by looking the equality for every coordinate, we have $n+1$ equations with $n+1$ unknowns. And the equations are independent if and only if $P$ is invertible in $\mathbb{Z}_p[X]/(Q\mathbb{Z}_p[X])$.

With your example $n=3$. \begin{align}((X^2 +1) \cdot( \lambda_0 + \lambda_1 X + \lambda_2 X^2 + \lambda_3 X^3) )\mod (X^4 + X + 1) = 1 \\ \lambda_0 + \lambda_1 X + (\lambda_2+\lambda_0) X^2 + (\lambda_3+ \lambda_1) X^3 + (\lambda_2 + \lambda_3X) X^4= 1 \\ \lambda_0 + \lambda_1 X + (\lambda_2+\lambda_0) X^2 + (\lambda_3+ \lambda_1) X^3 + (\lambda_2 + \lambda_3X) (-X-1)= 1 \\ (\lambda_0-\lambda_2) + (\lambda_1- \lambda_2 - \lambda_3) X + (\lambda_2+\lambda_0-\lambda_3) X^2 + (\lambda_3+ \lambda_1) X^3 = 1 \end{align}

If you solve the linear system, you will find the solution $\lambda_2=0$ and $\lambda_1=\lambda_3=\lambda_0=1$.

Ievgeni
  • 2,585
  • 1
  • 10
  • 32
1

Well, Sagemath can solve this, and as we know the SageMath uses Python. The reverse is also possible! Install the package by;

pip3 install sagemath

Now we are ready to use the SageMath code

k = GF(2)
R.<x> = k[]
k.extension(x^4 + x + 1, 'a')
print(k)

p = (x^2 + 1)

print(p)

q = p.inverse_mod(x^4 + x + 1)

print(q)

However, the R.<x> = k[] is not parsable by python. We have to use preparse to form python code.

preparse('R.<x> = k[]')
"R = k['x']; (x,) = R._first_ngens(1)"

So the python code is

from sage.all import *

F = GF(2) R = F['x']; (x,) = R._first_ngens(1) K = F.extension(x**4 + x + 1, 'a')

print(K)

p = (x2 + 1) print(p) q = p.inverse_mod(x4 + x + 1) print(q)

This outputs;

Finite Field in a of size 2^4
x^2 + 1
x^3 + x + 1

Thanks to John Palmieri on the preparse

kelalaka
  • 48,443
  • 11
  • 116
  • 196