(挑战编程_7_3)Euclid problem

http://www.programming-challenges.com/pg.php?page=downloadproblem&probid=110703&format=html

#include <iostream>
#include <cstdlib>
#include <vector>
#include <set>
#include <string>
#include <cstring>
#include <fstream>
#include <cassert>
#include <cmath>

using namespace std;

//#define _MY_DEBUG_

/*
	MainStructure: 主结构
*/
void MainStructure();

/*
	Process
*/
void Process();


/*
	欧几里得算法
*/
long gcd(long p, long q, long *x, long *y);

int main()
{
	MainStructure();
	return 0;
}

void MainStructure()
{
	
#ifdef _MY_DEBUG_
	string inputStr = "C:/Users/cao/Desktop/算法/要看的书/算法/2挑战编程/input/1.inp";
	//string inputStr = "D:/2挑战编程/input/110205.inp";
	string outputStr = "C:/Users/cao/Desktop/算法/要看的书/算法/2挑战编程/input/1.outp";
	ifstream fin;
	fin.open(inputStr);		

	cin.rdbuf(fin.rdbuf());	

	/*
	ofstream fout;
	fout.open(outputStr.c_str());
	cout.rdbuf(fout.rdbuf());
	*/

#endif

	Process();
			
}

void Process()
{
	unsigned a, b;
	while (cin >> a >> b)
	{
		long x, y;
		long ans = gcd(a, b, &x, &y);
		cout << x << ' ' << y << ' ' << ans << endl;
	}
}

/*
	x、y不是确定的
	如果x、y符合要求,则:
		(x+q*k, y-p*k)也符合要求
*/
long gcd(long p, long q, long *x, long *y)
{
	long x1, y1;
	long g;
	if (q > p)
	{
		return gcd(q, p, y, x);
	}

	if (q == 0)
	{
		*x = 1;
		*y = 0;
		return p;
	}

	g = gcd(q, p % q, &x1, &y1);
	*x = y1;
	*y = (x1 - long(p / (double)q) * y1);

	return g;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,Euclidean算法是用于计算两个非负整数a,b的最大公约数。而多项式Euclid除法是一种求解多项式的最大公约数的算法。下面是实现广义的多项式Euclid除法的步骤: 1.定义一个函数来计算两个多项式的最大公约数,函数名为poly_gcd(poly1, poly2)。 2.在函数中,首先判断两个多项式是否都为0,如果是,则返回0。 3.如果其中一个多项式为0,则返回另一个多项式。 4.如果两个多项式的次数相等,则计算它们的差,并递归调用poly_gcd()函数。 5.如果两个多项式的次数不相等,则将次数高的多项式除以次数低的多项式,并将余数作为新的多项式,递归调用poly_gcd()函数。 6.最后返回最大公约数。 下面是一个Python实现的多项式Euclid除法的例子: ```python def poly_gcd(poly1, poly2): if poly1 == [0] and poly2 == [0]: return [0] elif poly1 == [0]: return poly2 elif poly2 == [0]: return poly1 elif len(poly1) == len(poly2): return poly_gcd([poly1[i] - poly2[i] for i in range(len(poly1))], poly2) elif len(poly1) > len(poly2): q, r = poly_div(poly1, poly2) return poly_gcd(poly2, r) else: q, r = poly_div(poly2, poly1) return poly_gcd(poly1, r) def poly_div(poly1, poly2): n = len(poly1) - 1 m = len(poly2) - 1 q = [0] * (n - m + 1) r = poly1 for i in range(n - m + 1): q[n - m - i] = r[n - i] // poly2[m] for j in range(m + 1): r[n - i - j] -= q[n - m - i] * poly2[m - j] while r and r[-1] == 0: r.pop() return q, r ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值