exgcd模板--noip2012同余方程

模板。。不过还是讲一下

题目描述

求关于x的同余方程 ax≡1(mod)b的最小正整数解。


我们可以把这个方程转化一下,变成 ax+by=1

因为 题目保证有解,所以a,b互质

裸的exgcd

AC Code

#include<cstdio>
#include<iostream>
using namespace std;
int a,b;
int exgcd(int a,int b,int &x,int &y)
{
	if(b==0)
	{
		x=1;y=0;
		return a;
	}
	int t=exgcd(b,a%b,y,x);
	y-=a/b*x;
	return t;
}
int main()
{
	scanf("%d%d",&a,&b);
	int x,y;
	int gcd=exgcd(a,b,x,y);
	printf("%d",(x%b+b)%b);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/richard__luan/article/details/81109054