python-rsa-implementation/lib/arithmetics.py
2025-01-23 19:06:47 +01:00

36 lines
708 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
if b == 0:
return a
# return gcd(b, a % b) because gcd(a, b) = gcd(b, rem(a, b))
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 = A // M
t = M
M = A % M
A = t
t = y
y = x - q * y
x = t
if (x < 0):
x = x + m0
return x