exgcd extended Euclidean algorithm

Extended Euclid

  • Shu Pei Theorem: for any integer a, b, and their greatest common divisor d, x and y on the unknown variable linear equation: a x + b y = c ax+by=c solvable (iff c c is d d multiples)
  • Shu Pei theorem: if a x + b y = 1 ax+by=1 has a solution, then g c d ( a , b ) = 1 gcd(a,b)=1
  • Euclidean
  • int gcd(int a,int b)
    {
    	 return b==0?a:gcd(b,a%b);
    }
    
  • If you get a x c ( m o d b ) ax≡c(mod b) of a Special Solution X, then let r = b / g c d ( a , b ) r=b/gcd(a,b) , can be seen x x In [ 0 , r 1 ] [0,r-1] has a unique solution, and with the x = ( X % r + r ) % r x=(X\%r+r)\%r on the smallest non-negative integer solution can be determined x x the

board

A known a a and b b , solving equations a x + b y = g c d ( a , b ) a*x+b*y=gcd(a,b)
Note: The minimum solution is not obtained

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL extgcd(LL a, LL b, LL &x, LL &y) //扩展欧几里得,返回最大公约数(x,y 是变量参数直接返回)
{
	LL d,t;
	if(b==0)
	{
		x=1;
		y=0;
		return a; //返回最大公约数
	}
 	d=extgcd(b,a%b,x,y);
 	t=x-a/b*y;
	x=y;
	y=t;
 	return d; //返回最大公约数
}
int main()
{
 	LL a,b,x,y,d; //d 是最大公约数
 	cin>>a>>b;
 	d=extgcd(a,b,x,y);
 	cout<<a<<"*"<<x<<"+"<<b<<"*"<<y<<"="<<d<<endl;
 	return 0;
}
Frog appointments

Simple formula can be deformed
It must be judged negative! ! ! ! ! !(70 p t s pts tragedy TAT)

#include <bits/stdc++.h>
#define int long long
using namespace std;
int x,y,m,n,L,X,Y;
int exgcd(int a,int b,int &x,int &y){
	int d,t;
	if(b==0){
		x=1,y=0;
		return a;
	}
	d=exgcd(b,a%b,x,y);
	t=x-a/b*y;
	x=y;y=t;
	return d;
}
signed main(){
	//freopen("a.in","r",stdin);
	scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&L);
	int k=n-m,a=x-y;//简单式子变形
    if(k<0)
    {
        k=-k;
        a=-a;
    }//处理负数 
	int d=exgcd(k,L,X,Y);
	int r=L/d;
	if(a%d!=0){
		printf("Impossible");
		return 0;
	}
	else{
		printf("%lld\n",(a/d*X%r+r)%r);
		return 0;
	}
}
Published 37 original articles · won praise 11 · views 1950

Guess you like

Origin blog.csdn.net/weixin_42750325/article/details/102470014