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

}

相关推荐
Wei&Yan1 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
团子的二进制世界1 小时前
G1垃圾收集器是如何工作的?
java·jvm·算法
吃杠碰小鸡1 小时前
高中数学-数列-导数证明
前端·数学·算法
故事不长丨1 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
long3161 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
近津薪荼1 小时前
dfs专题4——二叉树的深搜(验证二叉搜索树)
c++·学习·算法·深度优先
熊文豪2 小时前
探索CANN ops-nn:高性能哈希算子技术解读
算法·哈希算法·cann
熊猫_豆豆2 小时前
YOLOP车道检测
人工智能·python·算法
艾莉丝努力练剑2 小时前
【Linux:文件】Ext系列文件系统(初阶)
大数据·linux·运维·服务器·c++·人工智能·算法
偷吃的耗子3 小时前
【CNN算法理解】:CNN平移不变性详解:数学原理与实例
人工智能·算法·cnn