[Applications] solve simple linear congruent equation
[Board (between coprime m)]
/ * Chinese remainder theorem board (base) provided with a remainder of c [i], modulo m [i], let M m [i] sum and then the final answer is c [i] (M / m [i]) and modM inv ((m / m [ i]), m [i]) of the solution is unique, and because each of m mod are different, so that just cover all situations. * / LL C [MAXN], m [MAXN], M; // I from the beginning. 1 LL exgcd (LL A, LL B, LL & X, LL & Y) { IF (! B) { X = . 1 , Y = 0 ; return A; } LL D = exgcd (B, A% B, Y, X); Y - = A / B * X; return D; } LL getInv (LL A, LL MOD) { LL X, Y, D; D =exgcd(a,mod,x,y); return d==1?(x%mod+mod)%mod:-1; } ll CRT(int n) { M=1; for(int i=1;i<=n;i++)M*=m[i]; ll ret=0; for(int i=1;i<=n;i++) ret=(ret+c[i] * (M/m[i]) %M * getInv(M/m[i],m[i]) )%M; return ret; }
[Board (extended)]
/ * Chinese remainder theorem board (extension) number mo not prime to each of the time * / LL m [MAXN], C [MAXN]; // beginning. 1 LL GCD (A LL, LL B) { return B! ? A: GCD (B, A% B); } LL exgcd (LL A, LL B, LL & X, LL & Y) { IF (! B) { X = . 1 , Y = 0 ; return A; } LL D exgcd = (B, A% B, Y, X); Y - = A / B * X; return D; } LL getInv (A LL, LL MOD) { LL X, Y; LL D=exgcd(a,mod,x,y); return d==1?(x+mod)%mod:-1; } ll exCRT(int n) { ll m1,m2,c1,c2,d; for(int i=2;i<=n;i++) { m1=m[i-1],m2=m[i],c1=c[i-1],c2=c[i]; d=gcd(m1,m2); if((c2-c1)%d)return -1;//此时无法合并 m[i] = m[i-1] * m[i] / d; c[i] = (c2-c1)/d * getInv(m1/d,m2/d) % ( m2 / d ) * m1 + c1; c[i] = ( c[i] % m[i] + m[i] ) % m[i]; } return c[n]; }
【prove】
I did not learn it, detailed look link
https://www.cnblogs.com/MashiroSky/p/5918158.html
【exercise】
hdu 1573
Reference [link]
https://blog.csdn.net/xiaoming_p/article/details/79672049