39 lines
760 B
Python
39 lines
760 B
Python
# Arithmetics functions implementaton
|
|
|
|
def modpow(a: int, b: int, m: int) -> int:
|
|
result = 1
|
|
while b > 0:
|
|
if (b & 1) > 0:
|
|
result = (result * a) % m
|
|
b = b >> 1
|
|
a = (a * a) % m
|
|
return result
|
|
|
|
def gcd(a: int, b: int) -> int:
|
|
if b == 0:
|
|
return a
|
|
return gcd(b, a % b)
|
|
|
|
def mod_inverse(A: int, M: int) -> int:
|
|
m0 = M
|
|
y = 0
|
|
x = 1
|
|
if (M == 1):
|
|
return 0
|
|
while (A > 1):
|
|
# q is quotient
|
|
q = A // M
|
|
t = M
|
|
# m is remainder now, process
|
|
# same as Euclid's algo
|
|
M = A % M
|
|
A = t
|
|
t = y
|
|
# Update x and y
|
|
y = x - q * y
|
|
x = t
|
|
# Make x positive
|
|
if (x < 0):
|
|
x = x + m0
|
|
return x
|
|
|