C++中使用扩展欧几里得求S,T

扩展欧几里得算法能够快速的求得gcd(a,b)的S,T值

下面是详细代码

#include<iostream>
using namespace std;
int main()
{
	int a, b;
	int s1, s2, x = 1, y = 0;//求s
	int t1, t2, g, f = 1;
	int j, k;
	int q[80];//存放Q
	s1 = x; s2 = y;
	cout << "请输入所需要求S,T的两数" << endl;
	cin >> a >> b;
	cout << endl;
	if (a > b)
	{
		j = a;
		k = b;
	}
	else
	{
		j = b;
		k = a;
	}
	int m; int x1, x2;
	m = j % k;
	cout << "商为:" << endl;
	q[0] = (j - m) / k;//Q0
	t1 = f; g = (-q[0]);
	t2 = g;
	cout << q[0] << " ";
	if (m == 0)
	{
		cout << endl << endl;
		cout << "S为:1" << endl;
		cout << "T为:";
		int x;
		x = j / k;
		cout << x << endl;
	}//判断是否为完全整除
	if (m != 0)
	{
		x2 = k;
		x1 = m;
		m = x2 % x1;
	}
	if (m != 0)
	{
		for (int i = 0; i < 100; i++)
		{
			int d, l;
			q[i + 1] = (x2 - m) / x1;//从Q1开始取并且存放
			cout << q[i + 1] << " ";
			s2 = s2 - (q[i + 1] * s1);
			l = t1 - ((t2)*q[i + 1]);
			x2 = x1;
			x1 = m;
			m = x2 % x1;
			t1 = t2; t2 = l;
			d = s2; s2 = s1; s1 = d;
			if (m == 0)
			{
				cout << endl << "S为:";
				cout << endl << s1<<endl;
				cout << endl << "T为:";
				cout << endl << l;
				break;
			}
		}
	}
	cout << endl;
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值