拓展的欧几里得算法

#include <iostream>
using namespace std;
int Euclidean(int n,int m,int &x,int &y)
{
	if(m ==0 )
	{
		x = 1;
		y = 0;
		return n;
	}
	int g = Euclidean(m, n%m, x, y );
	int t = x - (n / m )*y;
	x = y;
	y = t;
	return g;
}
int normalEuclidean(int n,int m)
{
   if( m ==0)
   	return n;
   else if (n % m ==0 )
   	return m;
   else return (m,n%m);
}
int main()
{
	int a,b,c;
	while(cin>>a>>b>>c)
	{
		int d = normalEuclidean(a, b) ;
       if(c %d ==0)
       {
         int tempa = a/d;
         int tempb = b/d;
         int tempc = c/d;
         int s,t;
	     int gcd = Euclidean(tempa,tempb,s,t);
	     cout<<gcd <<" is 1 ?"<<endl;
	     cout<<"special solu x is "<<(c/d)*s <<"  pecial solu y is "<<(c/d)*t<<endl;
	     cout<<" universal solu x is "<< (c/d)*s <<" + k* "<<b/d<< " and universal solu y is "<<(c/d)*t <<" -k* "<<a/d<<endl;
       }
	}
	system("pause");
    return 0;
}
上面的代码求得是丢番方程的求解,一个是特殊解,一个是通解,否则ax + by = c 就没有解了。因为这是两个变量的方程,所以不是没有就是无数。可以对变量的范围进行限制。
 Euclidean(tempa,tempb,s,t);这个函数是拓展的欧几里得算法。
下面是其中的一个实现。
#include <iostream>
using namespace std;
int Euclidean(int n,int m,int &x,int &y)
{
	if(m ==0 )
	{
		x = 1;
		y = 0;
		return n;
	}
	int g = Euclidean(m, n%m, x, y );
	int t = x - (n / m )*y;
	x = y;
	y = t;
	return g;
}
int main()
{
	int n,m;
	while(cin>>n>>m)
	{
      int x,y;
      if(Euclidean(n,m,x,y))
      {
      	cout<<x<<" is x "<<y<<" is y "<<Euclidean(n,m,x,y)<<" is gcd"<<endl;
      	cout<< x * n + y * m <<" == "<< Euclidean(n,m,x,y)<<endl;
      }
	}
	system("pause");
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值