gab
ExGCD indefinite equation for solving
\ [ax + by = c \
] a group of a particular solution. Commonly used in solving the congruence equation, such as inverse modulo under non-prime significance.
Derivation
main body
First, the necessary and sufficient conditions for the solvability of indefinite equation is given by Shu Pei Theorem
\ [\ gcd (a, b
) | c \] So we just focus on
\ [ax + by = \ gcd
(a, b) \] solution. (Solution of the original equation only, respectively (X \) \ , \ (Y \) is multiplied by \ (\ frac {c} { gcd (a, b)} \) can be determined)
(Hereinafter% refers to the generation of modulo operation)
Consider solving recursive. Suppose we already know the Diophantine equation
\ [bx + (a \%
b) y = \ gcd (b, a \% b) \] Solutions \ (x_1 \) , \ (Y_1 \) , i.e.
\ [b x_1 + (a \% b) y_1
= \ gcd (b, a \% b) \] now try to exploit this type of construct the solution of the original equation \ (X \) , \ (Y \) .
By the \ (\ gcd (a, b ) = \ gcd (b, a \% b) \) and \ (a \% b = a- \ lfloor \ frac {a} {b} \ rfloor b \)
Original formula into
\ [b x_1 + (a- \
lfloor \ frac {a} {b} \ rfloor b) y_1 = \ gcd (a, b) \] apart brackets
\ [b x_1 + a y_1 - \ lfloor \ frac ab \ rfloor b y_1 =
\ gcd (a, b) \] our goal is to construct a coefficient \ (a \) , \ (B \) of the original equation, therefore, finishing
\ [a y_1 + b ( x_1 - \ lfloor \ frac ab \
rfloor y_1) = \ gcd (a, b) \] successfully configured. Therefore,
\ [\ begin {aligned} x
& = y_1 \\ y & = x_1 - \ lfloor \ frac ab \ rfloor y_1 \ end {aligned} \] Boundary conditions of the Euclidean algorithm with recursive, when \ (B | a \) , the equation
\ [AX + by = GCD (a, B) = B \]
\ (X = 0 \) , \ (. 1 Y = \) i.e. a solution of the equation set Patent.
The minimum configuration \ (X \) Special Solution
Exgcd commonly used in the inverse element solution. In this case need to find a set of solutions, such \ (X \) minimum (positive integer range). Which can be formed.
We know that the general solution in the form of indeterminate equation for
\ [\ left \ {\ begin
{aligned} x & = x_0 + kb \\ y & = y_0 -. Ka \ end {aligned} \ right \] Therefore, in order to \ (X \) , for example, the smallest positive integer X = $ (x_0% B + B)% B \ (, then into an Indefinite equation \) Y = \ X FRAC * {CA} to {B} $ .
Code
namespace ExGcd{
ll x,y;
ll ExGcd(ll a,ll b){
ll ans;
if(a%b==0){
x=0;y=1;ans=b;
}else{
ans=ExGcd(b,a%b);
ll x1=x,y1=y;
x=y1;y=x1-a/b*y1;
}
return ans;
}
bool SolveEqu(ll a,ll b,ll c){
ll d=ExGcd(a,b);
if(c%d!=0) return 0;
x*=c/d;y*=c/d;
//以下为求最小的x
x=(x%b+b)%b;
y=(c-a*x)/b;
return 1;
}
}
//以下为求逆元
ll Inv(ll a,ll m){
ExGcd::SolveEqu(a,m,1);
return ExGcd::x;
}
Board questions: Luo Gu P1082 congruence equation , just change to change the above procedures.