CINTA作业二

写一个迭代版本的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 =0int 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值