扩展欧几里德算法

来源:互联网 发布:linux ldconfig 编辑:程序博客网 时间:2024/05/18 00:47
给一个二元一次方程ax+by=c求x和y的值(整点)。
根据欧几里德算法gcd(a,b)为A和B的最大公约数。
首先找到一个点(x, y)满足ax+by=gcd(a, b);注意,这里的x和y不一定是正数,也可能是负数和0,例如,gcd(6, 15)=3; 6*3-15*-1 = 3,其中x=3,y=-1.
下面是扩展欧几里得算法的代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include <stack>
#include <string>
#include <set>
#include <map>
#include <cstdlib>
#include <cmath>
#include <algorithm>
 
using namespace std;
 
void gcd(int a, int b, int &d, int &x, int &y) // 注意这里的int& d和int a.操作完后主函数的a的值不变, 而的值会变哦。
{
if (b == 0)
{
d=a;x=1;y=0;
}
else
{
gcd(b, a%b, d, y, x);
y -= x*(a/b);
}
}
int main()
{
int a, b, d;
while (scanf("%d%d", &a, &b, &d)!=EOF)
{
int x=0, y=0;
gcd(a, b, d, x, y);
printf("%d %d\n", x, y); // 输出最小的满足的点
}
return 0;
}
推理:
a*x1+b*y1 = gcd(a, b);
b*x2+(a%b)y2 = gcd(b, (a%b));
根据恒等定理得:x1=y2, y1=x2-(a/b)*y2;

0 0