Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/python/cpython/src/xgcd.py
1067 views
1
# A standard xgcd implementation for Python copied from a random webpage.
2
# This of course quickly overflows with Javascript "integers" = doubles'
3
def xgcd(a, b):
4
prevx, x = 1, 0
5
prevy, y = 0, 1
6
while b:
7
q, r = divmod(a, b)
8
x, prevx = prevx - q * x, x
9
y, prevy = prevy - q * y, y
10
a, b = b, r
11
return a, prevx, prevy
12
13
14
def bench_xgcd(n=10**6):
15
from time import time
16
t = time()
17
s = 0
18
for i in range(n):
19
s += xgcd(92250 - i, 922350 + i)[0]
20
print(s, time() - t)
21
22
23
def inverse_mod(a, N):
24
"""
25
Compute multiplicative inverse of a modulo N.
26
"""
27
if a == 1 or N <= 1: # common special cases
28
return a % N
29
[g, s, _] = xgcd(a, N)
30
if g != 1:
31
raise ZeroDivisionError
32
b = s % N
33
if b < 0:
34
b += N
35
return b
36
37
38
if __name__ == "__main__":
39
print("inverse_mod(7,15) = ", inverse_mod(7,15))
40
bench_xgcd()
41