Expand Euclid formula:
typedef long long LL; LL exgcd(LL a,LL b,LL &x,LL &y){ if(a==0&&b==0) return -1; if(b==0) { x=1;y=0; return a; } LL d=exgcd(b,a%b,y,x); y-=a/b*x; return d; }
Solutions ax + by = c Solution Set of:
typedef Long Long LL; LL X0, yO, KX, KY; BOOL LE (LL A, B LL, LL C) { // solution of linear equation ax + by = c LL X1, Y1; LL GCD = exgcd (A, B , X1, Y1); IF (% C GCD) return to false ; // no integer solution X0 = X1 * C / GCD; // set of solutions yO = Y1 * C / GCD; // set of solutions KX = B / GCD; KY = -a / GCD; return to true ; // solvable, the solution set is: (x0 + kx * t, y0 + ky * t) t is an integer }
The smallest positive integer x solving solutions:
/ * Solved smallest positive integer solutions of x * / typedef Long Long LL; void minxx ( int A, int B, int C, int x, int Y) { int GCD = exgcd (A, B, x, Y); LL X1, Y1, T; T = B / GCD; IF (T < 0 ) { T = - T; } X1 = (X + T) * (C / GCD); X1 = (X1% T + T)% T; Y1 = (X1 * CA) / B; the printf ( "x==%lld, y=%lld\n", x1, y1); return ; }
void minxx(ll a, ll b, ll c, ll x, ll y) { int gcd = exgcd(a, b, x, y); ll x1, y1, t; t = b / gcd; if( t<0 ) { t = -t; } x1 = x; x1 = (c/gcd*x1%t+t)%t; y1 = (c-a*x1)/b; printf("%lld %lld\n", x1, y1); return ; }
I ax≡b (mod n) with the equation for the unknown x solvable, if and only if gcd (a, n) | b (i.e. b% gcd (a, b) == 0), and the equation has a solution, Eq. there gcd (a, n) th solution.
Solving equation ax≡b (mod n) is equivalent to solving equation ax + ny = b, (x, y being an integer)
Solving linear congruence equation:
bool modular_linear_equation(int a,int b,int n) { int x,y,x0,i; int d=exgcd(a,n,x,y); if(b%d) return false; x0=x*(b/d)%n; //特解 for(i=1;i<d;i++) printf("%d\n",(x0+i*(n/d))%n); return true; }
Congruence equation ax≡b (mod n), if gcd (a, n) == 1, then the equation has only one solution.
In this case, if b == 1, congruence equation is ax = 1 (mod n), gcd (a, n) = 1.
In this case said determined modulo n x is a multiplication inverse element of a pair.
For congruence equation ax = 1 (mod n), gcd (a, n) = 1 is solved to solve the equation ax + ny = 1, x, y are integers.
ll inv(ll a, ll n) { ll d, x, y; d = exgcd(a, n, x, y); return (d==1)?(x%n+n)%n:-1; }