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

}

相关推荐
小羊在睡觉4 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
3DVisionary4 小时前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
好评笔记4 小时前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_468466854 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
_日拱一卒4 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
珂朵莉MM5 小时前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--束搜索
人工智能·算法
Omics Pro6 小时前
首个!外源天然产物综合性代谢图谱
数据库·人工智能·算法·机器学习·r语言
voidmort6 小时前
3. 微调(Fine-tuning)与强化学习(RL)的核心思想
python·深度学习·算法
人道领域6 小时前
【LeetCode刷题日记】669.修剪二叉搜索树
开发语言·python·算法
QiLinkOS7 小时前
【从实验室到商业战场:发明专利如何重塑科技与企业的共生生态】
大数据·c语言·数据结构·c++·人工智能·单片机·算法