"Extended Euclidean algorithm"의 두 판 사이의 차이
ph
잔글 |
잔글 |
||
| 27번째 줄: | 27번째 줄: | ||
if a<n: | if a<n: | ||
a += n | a += n | ||
| − | + | r, x, _ = exteuclid(a, n) | |
| + | # caution: if r>1, a is not invertible. | ||
if x<0: | if x<0: | ||
x += n | x += n | ||
2017년 8월 11일 (금) 16:00 판
python code is as follows,
def exteuclid(m, n, s0=1, s1=0, t0=0, t1=1):
# s0 := s_{i-1}
# s1 := s_i
# t0 := t_{i-1}
# t1 := t_i
assert m>=n
q = m/n
r = m%n
s = s0 - q*s1
t = t0 - q*t1
if r==0:
return n, s1, t1
else:
return exteuclid(n, r, s1, s, t1, t)
#test
#print exteuclid(240, 46)
#(2, -9, 47)
Modular multiplicative inverse는 다음으로 구한다.
def invmult(a, n):
if a<n:
a += n
r, x, _ = exteuclid(a, n)
# caution: if r>1, a is not invertible.
if x<0:
x += n
return x
#test
#print invmult(234242, 11117) #coprime
#10154
ref. coprime test