扩展欧几里得(acwing877)

给a,b求使ax+by=gcd(a,b),成立的x,y;

思路:

整个过程可以分为两部分,一部分是求gcd(a,b),当函数递归回来时,求x,y;

递归回来时: b*y+(a-(a/b)*b)*x=d(d为gcd(a,b));

求当前a*x+b*y=d,的x,y;

a*x+b(y-a/b*x)=d;

x=x;

y=y-a/b*x;

代码:

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>

#include<cstdio>

#include<cstdlib>

#include<string>

#include<cstring>

#include<cmath>

#include<ctime>

#include<algorithm>

#include<utility>

#include<stack>

#include<queue>

#include<vector>

#include<set>

#include<math.h>

#include<unordered_map>

#include<map>

using namespace std;

typedef long long LL;

#define per(i,a,b) for(int i=a;i<=b;i++)

const int N = 1e5 + 100;

LL n, k;

int exgcd(int a, int b, int& x, int & y)

{

if (!b)//a*1+b*0=a;

{

x = 1;

y = 0;

return a;

}

int d=exgcd(b, a % b, y, x);//逆转x,y方便求递归回来时x,y

y = y - (a / b)*x;

return d;

}

int main()

{

int a, b, x, y;

scanf("%lld", &n);

while (n--)

{

scanf("%d%d", &a, &b);

exgcd(a, b, x, y);

printf("%d %d\n", x, y);

}

return 0;

}

相关推荐
JieE2127 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2121 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack202 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树2 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦3 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050733 天前
(一)小红的数组操作
算法·编程语言