写一个迭代版本的gcd算法程序
#include<iostream>
using namespace std;
int gcd(int a,int b)
{
int temp;
while(b!=0)
{
temp = a;
a = b;
b = temp % a;
}
return a;
}
int main()
{
int A,B;
cin>>A>>B;
cout<<gcd(A,B);
return 0;
}
写一个二进制gcd算法程序(bgcd)
#include<iostream>
using namespace std;
int bgcd(int a,int b)
{
int flag=0;
while(((a|b)&1)==0)
/*a|b是位运算,先把a,b转化成二进制,然后位相或,有1出1,无1出0
a&1用来判断该数是否能被2整除*/
{
a>>=1;//a和b同时右移一位,等价于a,b除以2;
b>>=1;
flag++;
}
while((a&1)==0)
{
a=a>>1;
}
while(b!=0)
{
while((b&1)==0)
{
b=b>>1;
}
if(a>b)
{
tmp=a;
a=b;
b=tmp;
}
b=b-a;
}
return (a<<flag);//a向左移flag位,等价于a=a*pow(2,flag)
}
int main()
{
int A,B;
cin>>A>>B;
cout<<bgcd(A,B)<<endl;
return 0;
}
写一个迭代版本的egcd程序
#include<iostream>
using namespace std;
int *egcd(int a,int b)
{
int r0=1,r1=0,s0=0,s1=1;
while(b!=0)
{
int q=a/b;
int r_tmp=r0,s_tmp=s0;
a=b;
b=a%b;
r0=r1;
r1=r_tmp-q*r1;
s0=s1;
s1=s_tmp-q*s1;
}
int *result = new int[3];
result[0] = a;
result[1] = r0;
result[2] = s0;
return result;
}
int main()
{
int A,B;
cin>>A>>B;
int *result = egcd(A,B);
cout<<result[0]<<" "<<result[1]<<" "<<result[2]<<endl;
return 0;
}
写一个递归版本的egcd程序
#include<iostream>
using namespace std;
int *egcd(int a, int b,int r0 =1,int r1= 0,int s0 =0,int s1 = 1)
{
int *result = new int[3];
result[0] = a;
result[1] = r0;
result[2] = s0;
if (b == 0)
return result;
int q = a / b;
return egcd(b, a%b, r1, r0-q*r1, s1 ,s0 - q * s1);
}
int main()
{
int *result = egcd(30, 23);
cout<<result[0]<<" "<<result[1]<<" "<<result[2]<<endl;
return 0;
}
写一个二进制egcd算法程序
#include<iostream>
void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
int* begcd(int a, int b) {
int r = a;
int _r = b;
int k = 0;
while (!(r & 1) && !(_r & 1)) {
r >>= 1;
_r >>= 1;
k++;
}
int _a = r;
int _b = _r;
int x = 1; int y = 0; int _x = 0; int _y = 1;
while (_r) {
while (!(r & 1)) {
r >>= 1;
if (!(x & 1) && !(y & 1)) {
x >>= 1; y >>= 1;
}
else {
x = (x + _b) >> 1;
y = (y - _a) >> 1;
}
}
while (!(_r & 1)) {
_r >>= 1;
if ((_x&_y) & 1) {
_x >>= 1; _y >>= 1;
}
else {
_x = (_x + _b) >> 1;
_y = (_y - _a) >> 1;
}
}
if (_r < r) {
swap(&r, &_r);
swap(&x, &_x);
swap(&y, &_y);
}
_r -= r; _x -= x; _y -= y;
}
int *res = (int*)malloc(sizeof(int) * 3);
res[0] = x; res[1] = y; res[2] = (r << k);
return res;
}