贝祖定理
对于
a
,
b
a,b
a,b是任意两个正整数,则存在整数
s
,
t
s,t
s,t使得
s
a
+
t
b
=
(
a
,
b
)
sa+tb=(a,b)
sa+tb=(a,b)。其中
(
a
,
b
)
(a,b)
(a,b)是
a
,
b
a,b
a,b的最大公因数。
其证明也就是求最大公因数的逆过程。这里使用辗转相除法来证明。
不妨设
a
>
b
a> b
a>b,则有下列等式成立:
a
=
q
0
b
+
r
0
,
(
0
<
r
0
<
b
)
b
=
q
1
r
0
+
r
1
,
(
0
<
r
1
<
r
0
)
r
0
=
q
2
r
1
+
r
2
,
(
0
<
r
2
<
r
1
)
⋮
r
n
−
2
=
q
n
r
n
−
1
+
r
n
,
(
0
<
r
n
<
r
n
−
1
)
r
n
−
1
=
q
n
+
1
r
n
+
r
n
+
1
,
(
r
n
+
1
=
0
)
\begin{aligned} a&=q_0b+r_0,(0<r_0<b)\\ b&=q_1r_0+r_1,(0<r_1<r_0)\\ r_0&=q_2r_1+r_2,(0<r_2<r_1)\\ &\vdots \\ r_{n-2}&=q_nr_{n-1}+r_n,(0<r_n<r_{n-1})\\ r_{n-1}&=q_{n+1}r_n+r_{n+1},(r_{n+1}=0) \end{aligned}
abr0rn−2rn−1=q0b+r0,(0<r0<b)=q1r0+r1,(0<r1<r0)=q2r1+r2,(0<r2<r1)⋮=qnrn−1+rn,(0<rn<rn−1)=qn+1rn+rn+1,(rn+1=0)
根据辗转相除法,
r
n
=
(
a
,
b
)
r_n=(a,b)
rn=(a,b)
现在,将上述等式倒过来,有
r
n
=
−
q
n
r
n
−
1
+
r
n
−
2
,
r
n
−
1
=
−
q
n
−
2
r
n
−
2
+
r
n
−
3
,
⋮
r
2
=
−
q
2
r
1
+
r
0
,
r
1
=
−
q
1
r
0
+
b
,
r
0
=
−
q
0
b
+
a
.
\begin{aligned} r_n&=-q_nr_{n-1}+r_{n-2},\\ r_{n-1}&=-q_{n-2}r_{n-2}+r_{n-3},\\ &\vdots\\ r_2&=-q_2r_1+r_0,\\ r_1&=-q_1r_0+b,\\ r_0&=-q_0b+a. \end{aligned}
rnrn−1r2r1r0=−qnrn−1+rn−2,=−qn−2rn−2+rn−3,⋮=−q2r1+r0,=−q1r0+b,=−q0b+a.
然后逐步消去
r
n
−
1
,
r
n
−
2
,
r
n
−
3
,
⋯
,
r
0
r_{n-1},r_{n-2},r_{n-3},\cdots,r_0
rn−1,rn−2,rn−3,⋯,r0,便找到了对应的
s
,
t
s,t
s,t。
如果令
s
−
2
=
1
,
s
−
1
=
0
,
s
j
=
(
−
q
j
)
s
j
−
1
+
s
j
−
2
,
t
−
2
=
0
,
t
−
1
=
1
,
s
j
=
(
−
q
j
)
t
j
−
1
+
t
j
−
2
.
s_{-2}=1,s_{-1}=0,s_j=(-q_j)s_{j-1}+s_{j-2},\\ t_{-2}=0,t_{-1}=1,s_j=(-q_j)t_{j-1}+t_{j-2}.
s−2=1,s−1=0,sj=(−qj)sj−1+sj−2,t−2=0,t−1=1,sj=(−qj)tj−1+tj−2.
根据递推公式,就可以轻易算出
s
,
t
s,t
s,t了。而计算的过程就是扩展欧几里得算法。
c++示例代码
#include<iostream>
#include<vector>
using namespace std;
// ensure that a > b
vector<int> exgcd(int a,int b,int s1=1,int s2=0,int t1=0,int t2=1){
int r=a%b;
if(r==0){
return {b,s2,t2};
}
int q=a/b;
int s3=-q*s2+s1;
int t3=-q*t2+t1;
return exgcd(b,r,s2,s3,t2,t3);
}
int main(){
int a,b;
cout<<"ensure that a>b."<<endl;
cout<<"please input a "<<endl;
cin>>a;
cout<<"please input b "<<endl;
cin>>b;
vector<int> res=exgcd(a,b);
cout<<"s is "<<res[1]<<endl;
cout<<"t is "<<res[2]<<endl;
cout<<"(a,b) is "<<res[0]<<endl;
cout<<"sa + tb = "<<res[1]*a+res[2]*b<<endl;
}
大整数扩展欧几里得算法
当
(
a
,
b
)
=
1
(a,b)=1
(a,b)=1时,往往使用扩展欧几里得算法来求逆元,但是,通常的应用都是大整数,int类型显然太小了。在gmp库中实现了扩展欧几里得算法。
其函数原型为:
void mpz_gcdext (mpz_t g, mpz_t s, mpz_t t, const mpz_t a, const mpz_t b)
#include<iostream>
#include<gmpxx.h>
#include<gmp.h>
using namespace std;
int main(){
mpz_class a,b,s,t;
cout<<"Please input a and b (a<b)"<<endl;
cout<<"a:";
cin>>a;
cout<<"b:";
cin>>b;
mpz_class gcd;
mpz_gcdext(gcd.get_mpz_t(),s.get_mpz_t(),t.get_mpz_t(),a.get_mpz_t(),b.get_mpz_t());
cout<<"s is:"<<s<<endl;
cout<<"t is:"<<t<<endl;
cout<<"the gcd is:"<<gcd<<endl;
cout<<"sa + tb = "<<s*a+t*b<<endl;
return 0;
}