Python中的模块化乘法逆函数

问题描述 投票:74回答:11

一些标准的Python模块是否包含一个函数来计算一个数字的modular multiplicative inverse,即y = invmod(x, p)这样的数字x*y == 1 (mod p)?谷歌似乎没有给出任何好的提示。

当然,人们可以想出自制的10线extended Euclidean algorithm,但为什么要重新发明轮子。

例如,Java的BigIntegermodInverse方法。 Python没有类似的东西吗?

python algorithm
11个回答
105
投票

也许有人会发现这很有用(来自wikibooks):

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

0
投票

好吧,我在python中没有函数但我在C中有一个函数可以很容易地转换为python,在下面的c函数中扩展的欧几里得算法用于计算逆mod。

int imod(int a,int n){
int c,i=1;
while(1){
    c = n * i + 1;
    if(c%a==0){
        c = c/a;
        break;
    }
    i++;
}
return c;}

Python函数

def imod(a,n):
  i=1
  while True:
    c = n * i + 1;
    if(c%a==0):
      c = c/a
      break;
    i = i+1

  return c

参考上述C函数取自以下链接C program to find Modular Multiplicative Inverse of two Relatively Prime Numbers


0
投票

这是一个简洁的1-liner,无需使用任何外部库。

# Given 0<a<b, returns the unique c such that 0<c<b and a*c == gcd(a,b) (mod b).
# In particular, if a,b are relatively prime, returns the inverse of a modulo b.
def invmod(a,b): return 0 if a==0 else 1 if b%a==0 else b - invmod(b%a,a)*b//a

请注意,这实际上只是egcd,简化以仅返回单个感兴趣的系数。


0
投票

来自cpython实现source code

def invmod(a, n):
    b, c = 1, 0
    while n:
        q, r = divmod(a, n)
        a, b, c, n = n, c, b - q*c, r
    # at this point a is the gcd of the original inputs
    if a == 1:
        return b
    raise ValueError("Not invertible")

根据此代码上面的注释,它可以返回小的负值,因此您可以检查是否为负数,并在返回b之前添加n为负数。


-1
投票

上面的许多链接都会在2017年1月23日被破坏。我找到了这个实现:https://courses.csail.mit.edu/6.857/2016/files/ffield.py


51
投票

如果你的模数是素数(你称之为p),那么你可以简单地计算:

y = x**(p-2) mod p  # Pseudocode

或者在Python中:

y = pow(x, p-2, p)

以下是在Python中实现了一些数论功能的人:http://www.math.umbc.edu/~campbell/Computers/Python/numbthy.html

以下是在提示符处完成的示例:

m = 1000000007
x = 1234567
y = pow(x,m-2,m)
y
989145189L
x*y
1221166008548163L
x*y % m
1L

19
投票

您可能还想查看gmpy模块。它是Python和GMP多精度库之间的接口。 gmpy提供了一个反转功能,可以完全满足您的需求:

>>> import gmpy
>>> gmpy.invert(1234567, 1000000007)
mpz(989145189)

更新的答案

如@hyh所述,如果逆不存在,则gmpy.invert()返回0。这符合GMP的mpz_invert()功能的行为。 gmpy.divm(a, b, m)a=bx (mod m)提供了一般解决方案。

>>> gmpy.divm(1, 1234567, 1000000007)
mpz(989145189)
>>> gmpy.divm(1, 0, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 9)
mpz(7)

divm()将在gcd(b,m) == 1时返回一个解,并在乘法逆不存在时引发异常。

免责声明:我是gmpy库的当前维护者。

更新的答案2

当反向不存在时,gmpy2现在正确引发异常:

>>> import gmpy2

>>> gmpy2.invert(0,5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: invert() no inverse exists

8
投票

这是CodeFights的单线;它是最短的解决方案之一:

MMI = lambda A, n,s=1,t=0,N=0: (n < 2 and t%N or MMI(n, A%n, t, s-A//n*t, N or n),-1)[n<1]

如果-1A中没有乘法逆,它将返回n

用法:

MMI(23, 99) # returns 56
MMI(18, 24) # return -1

解决方案使用Extended Euclidean Algorithm


4
投票

Sympy是一个用于符号数学的python模块,如果你不想实现自己的(或者如果你已经使用Sympy),它有一个内置的模块化反函数:

from sympy import mod_inverse

mod_inverse(11, 35) # returns 16
mod_inverse(15, 35) # raises ValueError: 'inverse of 15 (mod 35) does not exist'

这似乎没有在Sympy网站上记录,但这里是文档字符串:Sympy mod_inverse docstring on Github


2
投票

这是我的代码,它可能很草率但无论如何它似乎对我有用。

# a is the number you want the inverse for
# b is the modulus

def mod_inverse(a, b):
    r = -1
    B = b
    A = a
    eq_set = []
    full_set = []
    mod_set = []

    #euclid's algorithm
    while r!=1 and r!=0:
        r = b%a
        q = b//a
        eq_set = [r, b, a, q*-1]
        b = a
        a = r
        full_set.append(eq_set)

    for i in range(0, 4):
        mod_set.append(full_set[-1][i])

    mod_set.insert(2, 1)
    counter = 0

    #extended euclid's algorithm
    for i in range(1, len(full_set)):
        if counter%2 == 0:
            mod_set[2] = full_set[-1*(i+1)][3]*mod_set[4]+mod_set[2]
            mod_set[3] = full_set[-1*(i+1)][1]

        elif counter%2 != 0:
            mod_set[4] = full_set[-1*(i+1)][3]*mod_set[2]+mod_set[4]
            mod_set[1] = full_set[-1*(i+1)][1]

        counter += 1

    if mod_set[3] == B:
        return mod_set[2]%B
    return mod_set[4]%B

2
投票

上面的代码不会在python3中运行,并且与GCD变体相比效率较低。但是,此代码非常透明。它引发了我创建一个更紧凑的版本:

def imod(a, n):
 c = 1
 while (c % a > 0):
     c += n
 return c // a

1
投票

为了找出模乘法逆,我建议使用扩展欧几里德算法,如下所示:

def multiplicative_inverse(a, b):
    origA = a
    X = 0
    prevX = 1
    Y = 1
    prevY = 0
    while b != 0:
        temp = b
        quotient = a/b
        b = a%b
        a = temp
        temp = X
        a = prevX - quotient * X
        prevX = temp
        temp = Y
        Y = prevY - quotient * Y
        prevY = temp

    return origA + prevY

1
投票

我从这个线程尝试不同的解决方案,最后我使用这个:

def egcd(self, a, b):
    lastremainder, remainder = abs(a), abs(b)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
        x, lastx = lastx - quotient*x, x
        y, lasty = lasty - quotient*y, y
    return lastremainder, lastx * (-1 if a < 0 else 1), lasty * (-1 if b < 0 else 1)


def modinv(self, a, m):
    g, x, y = self.egcd(a, m)
    if g != 1:
        raise ValueError('modinv for {} does not exist'.format(a))
    return x % m

Modular_inverse in Python

© www.soinside.com 2019 - 2024. All rights reserved.