Topic Link: Click to open the link
The main topic: there is a number X,x%ai = ri, give n to Ai and ri, ask what is the smallest nonnegative integer of x, if there is no output-1
The Chinese remainder theorem of non-reciprocity:
x%a1= R1; X%A2 = R2; Set K1,K2 to get x = A1*k1 + r1, x = a2*k2+r2
So a1*k1+r1 = a2*k2+r2--and A1*K1 = (R2-R1) + A2*K2----> a2 the entire equation, get (a1*k1)%a2 = (R2-R1)%a2, there is only one unknown K1, Using the extended gcd to find the K1, calculate x = A1*k1+r1
This x is just satisfying x%a1= r1; x%a2 = R2; not necessarily satisfying x%a3 = R3, so finding X is just a special solution to the real solution, the true rescue ans
So Ans≡x%lca (A1,A2)--only ans is an unknown, so convert the two formulas to a formula so that the constant merging, seeking the final result.
Judge whether there is a solution, in the extension gcd K1.
#include <cstdio> #include <cstring> #include <algorithm> #define LL __int64using namespace Std;void GCD (LL a,ll b,ll &d,ll &x,ll &y) {if (b = = 0) {d = A; x = 1; y = 0; } else {gcd (b,a%b,d,y,x); y = (A/b) *x; } return; int main () {LL K, A1, A2, R1, R2, D, X, y; while (scanf ("%i64d", &k)!=eof) {LL flag = 1; scanf ("%i64d%i64d", &A1, &R1); k--; while (k--) {scanf ("%i64d%i64d", &A2, &R2); GCD (A1,a2,d,x,y); if ((R2-R1)%d) flag = 0; if (flag) {x = (R2-R1)/d*x; y = a2/d; x = (x%y +y)%y; R1 = x*a1 + r1; A1 = (A1*A2)/D; }} gcd (1,a1,d,x,y); if (r1%d) flag = 0; if (flag = = 0) printf (" -1\n"); else {x = R1/d*x; y = a1/d; x = (x%y+y)%y; printf ("%i64d\n", X); }} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Poj2891--strange-to-Express integers (the Chinese remainder theorem of non-reciprocal vegetarian)