your programing

Python의 모듈 식 곱셈 역함수

lovepro 2020. 10. 4. 12:58
반응형

Python의 모듈 식 곱셈 역함수


일부 표준 파이썬은 계산하는 함수를 포함하는 모듈 않는 모듈 역수 수의, 즉 다수의 y = invmod(x, p)그러한를 x*y == 1 (mod p)? Google은 이에 대해 좋은 힌트를주지 않는 것 같습니다.

물론, 확장 된 유클리드 알고리즘 의 10 줄짜리 집에서 만든 10 줄짜리 알고리즘을 생각해 낼 수 있지만 왜 바퀴를 다시 발명해야할까요?

예를 들어 Java의 BigIntegerhas modInverse메소드. 파이썬에도 비슷한 것이 없습니까?


아마도 누군가가 유용하다고 생각할 것입니다 ( 위키 북에서 ) :

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

모듈러스가 소수 (당신은 그것을라고 부른다 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

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

다음은 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]

곱셈 역이 없으면 반환 -1됩니다 .An

용법:

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

이 솔루션은 확장 유클리드 알고리즘을 사용합니다 .


심볼릭 수학을위한 파이썬 모듈 인 Sympy 에는 자체 구현을 원하지 않는 경우 (또는 이미 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 웹 사이트에 문서화되지 않은 것 같지만 여기에 독 스트링이 있습니다 : Github의 Sympy mod_inverse docstring


여기 내 코드가 있습니다. 엉성 할 수 있지만 어쨌든 저에게는 작동하는 것 같습니다.

# 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

The code above will not run in python3 and is less efficient compared to the GCD variants. However, this code is very transparent. It triggered me to create a more compact version:

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

To figure out the modular multiplicative inverse I recommend using the Extended Euclidean Algorithm like this:

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

I try different solutions from this thread and in the end I use this one:

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


Well, I don't have a function in python but I have a function in C which you can easily convert to python, in the below c function extended euclidian algorithm is used to calculate inverse 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 Function

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

Reference to the above C function is taken from the following link C program to find Modular Multiplicative Inverse of two Relatively Prime Numbers


Here is a concise 1-liner that does it, without using any external libraries.

# 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

Note that this is really just egcd, streamlined to return only the single coefficient of interest.


from the cpython implementation 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")

according to the comment above this code, it can return small negative values, so you could potentially check if negative and add n when negative before returning b.


Many of the links above are broken as for 1/23/2017. I found this implementation: https://courses.csail.mit.edu/6.857/2016/files/ffield.py

참고URL : https://stackoverflow.com/questions/4798654/modular-multiplicative-inverse-function-in-python

반응형