1、给出Bezout定理的完整证明
构造一个集合 S={am+bn:m,n且am+bn>0}
由良序定理,我们可以得到该非空集合 S 中必然有一个最小数 d = ar + bs, r,s,记d为gcd(a,b)
令a=dq+r',0≤r'<d
如果r'>0,r'=a-dq=a-(ar+bs)q=a-arq-bsq=a(1-rq)+b(-sq)
这与d是s中最小元素这一事实相反
因此r'=0,d整除a,同理得d整除b,所以d是a和b的公因子
假设存在d'可以同时整除a,b
令a=d'h,b=d'k
则d=ar+bs=d'hr+d'ks=d'(hr+ks)
所以d'整除d
所以存在一对整数 r,s 使得 gcd(a, b) =d= ar + bs,
2、实现GCD算法的迭代版本
#include<iostream>
using namespace std;
int gcd(int a, int b)
{
if (b == 0)return a;
int temp = 0;
while (b)
{
temp = a;
a = b;
b = temp % a;
}
return a;
}
int main()
{
int a,b;
cout << "请输入两个整数的值" << endl;
cin >> a >> b;
cout << "这两个整数的最大公因数为" << gcd(a, b)<< endl;
system("pause");
return 0;
}
3、实现EGCD算法。输入:a、b两个整数,输出:r、s、d三个整数,满足ar + bs =d
#include<iostream>
using namespace std;
void egcd(int a, int b)
{
int r1 = 1, r2 = 0;
int s1 = 0, s2 = 1;
int temp1,temp2,temp3;
while (a % b != 0)
{
int c = a % b;
int d = a / b;
temp1 = a;
a = b;
b = temp1 % a;
temp2 = s1;
s1 = s2;
s2 = temp2 - d*s1;
temp3 = r1;
r1 = r2;
r2 = temp3 - d*r1;
}
cout << "r=" << r2 << " " << "s=" << s2 << " " << "d=" << b <<" ";
cout << "满足ar+bs=d" << endl;
}
int main()
{
int a, b;
cout << "请输入两个整数的值" << endl;
cin >> a >> b;
egcd(a, b);
system("pause");
return 0;
}
4、实现一种批处理版本的GCD算法,即,给定一个整数数组,输出其中所有整数的最大公因子。输入:一个整数数组a;输出:一个整数d,是a数组中所有整数的最大公因子
#include<iostream>
using namespace std;
int gcd(int a, int b)
{
if (b == 0)return a;
int temp = 0;
while (b)
{
temp = a;
a = b;
b = temp % a;
}
return a;
}
void agcd(int a[],int n)//n为数组长度
{
if (n == 1)
cout << "该数组所有整数的最大公因子为" << a[0] << endl;
int d = gcd(a[0], a[1]);
for (int i = 2; i < n-1; i++)
{
d = gcd(d, a[i]);
}
cout << "该数组所有整数的最大公因子为" << d << endl;
}