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

}

相关推荐
Humbunklung2 小时前
Rust 控制流
开发语言·算法·rust
鑫鑫向栄3 小时前
[蓝桥杯]取球博弈
数据结构·c++·算法·职场和发展·蓝桥杯·动态规划
m0_634448894 小时前
从上下文学习和微调看语言模型的泛化:一项对照研究
学习·算法·语言模型
Once_day4 小时前
代码训练LeetCode(21)跳跃游戏2
算法·leetcode
德先生&赛先生5 小时前
LeetCode-934. 最短的桥
算法·leetcode·职场和发展
CCF_NOI.6 小时前
洛谷P12610 ——[CCC 2025 Junior] Donut Shop
算法
鑫鑫向栄7 小时前
[蓝桥杯]模型染色
数据结构·c++·算法·职场和发展·蓝桥杯
1白天的黑夜19 小时前
栈-20.有效的括号-力扣(LeetCode)
c++·算法·leetcode