Euclidean Algorithm
Euclidean Algorithm
欧几里得算法也称辗转相除法,运用于求解两数的最大公因子
为了避免只会用库函数的尴尬境况,还是来复习一下它的原理
对于两个数a,b如何求解a,b的最大公因数呢?
欧几里得给出了如下算法
a=bq1+r1
b=r1q2+r2
r1=r2q3+r3
···
rn-1=rnqn+1
最后得到gcd(a,b)=rn
but why?
首先算法必在有限步骤内结束,因为每一步的余数都在递减,有限步骤后为0
不妨设gcd(a,b)=d
=>d|a-bq1 即d|r1
同样操作下去=>d|rk直到rk=0
于是我们可以得到d|rn
现在我们从后往前由rn|rn-1=>rn|rn-2
=>rn|a;rn|b=>rn|d
综上rn=d
代码实现
def gcd(a,b):
r=a%b
if r:
return gcd(b,r)
else:
return b
ps:
We also can think of (Z,+) to understand gcd
Let a,b ∈Z not both 0,then Z×a+Z×b=Z×d
a)d|a&d|b
b)if an integers e divides both a and b,it also divides d
c)∃r,s: d=ra+sb
pf:
1)∵a∈Z×d&b∈Z×d
=>d|a&d|b
2)e|a&e|b=>e|ra+sb
∵d∈Z×d=>d=k1a+k2b
=>e|d
3)by the conditions it's obvious
We know that d is the greatest common divisor of a and b
meanwhile we learn some property of d like c)
And then we prove the Euclidean algorithm use group structure
suppose we have a=qb+z
=>for any integers r,s: ra+sb=r(qb+z)+sb=(rq+s)b+rz
=>Z×a+Z×b⊆Z×b+Z×z
in a similar way
for any integers r,s: rb+sz=rb+s(a-qb)=sa+(r-sq)b
=>Z×b+Z×z⊆Z×a+Z×b
in conclusion Z×a+Z×b=Z×b+Z×z
on the basis of group theory wo know
Z×a+Z×b=Z×d1
Z×b+Z×z=Z×d2
=>d1=d2 means gcd(a,b)=gcd(b,z)(※)
(※) is the essence of Euclidean algorithm
Extended Euclidean Algorithm
前面我们用群论的知识证明了这样一个事实
对于不全为0的数a,b存在r,s使得
ra+sb=gcd(a,b)
欧几里得拓展算法就是描述的寻找这样的r与s的过程
首先我们有
r1a+s1b=gcd(a,b)
同样的方式可得
r2b+s2(a%b)=gcd(b,a%b)
由欧几里得算法=>r1a+s1b=r2b+s2(a%b)
a%b=a-[\(\frac{a}{b}\)]×b
=>r1a+s1b=r2b+s2(a-[\(\frac{a}{b}\)]×b)=s2a+(r2-s2×[\(\frac{a}{b}\)])b
对比系数我们很容易得到一个寻找的方案
即r1=s2,s1=r2-s2×[\(\frac{a}{b}\)]
由于欧几里得算法能在有限步骤内完成,可知扩展欧几里得算法也是在有限步骤内完成,完成时r=0;s=1
代码实现
def xgcd(a,b):
if a%b==0:
return 0,1
else:
r,s=xgcd(b,a%b)
return s,r-s*(a//b)

浙公网安备 33010602011771号