扩展欧几里得(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;

}

相关推荐
Maỿbe12 分钟前
力扣hot图论部分
算法·leetcode·图论
LYFlied20 分钟前
【每日算法】LeetCode 78. 子集
数据结构·算法·leetcode·面试·职场和发展
月明长歌24 分钟前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树
子枫秋月25 分钟前
C++字符串操作与迭代器解析
数据结构·算法
鹿角片ljp25 分钟前
力扣234.回文链表-反转后半链表
算法·leetcode·链表
(●—●)橘子……26 分钟前
记力扣1471.数组中的k个最强值 练习理解
数据结构·python·学习·算法·leetcode
oioihoii29 分钟前
C++共享内存小白入门指南
java·c++·算法
Bruce_kaizy31 分钟前
c++图论————图的基本与遍历
c++·算法·图论
l1t34 分钟前
利用小米mimo为精确覆盖矩形问题C程序添加打乱函数求出更大的解
c语言·开发语言·javascript·人工智能·算法
亭上秋和景清37 分钟前
strlen;strcpy ;strcat
算法