Question: http://poj.org/problem? Id = 1061
Conclusion: extending Euclidean, ax + by = N, A and B can be positive and negative, and X can be positive and negative.
After finding the exclusive solution x, find the minimum positive integer solution. B is used at the beginning, and the result is wa. Later we found that ax/(a, B) + by/(a, B) = N/(A, B ). In this case, x + K * B/(A, B );
That is, t = B/(a, B), T may be negative, so to turn positive, t = | T |, then X0 = (X % B + B) % B, the special solution x may be negative;
If you use while (x> T) {X-= t} while (x <0) {x + = t} instead of using the formula for finding the limit, it takes a lot of time, this method is 422 ms, and the formula is 0 ms.
If the data size is big, it is very likely that the timeout will occur.
Source code:
# Include <stdio. h> typedef long ll; int X, Y, m, n, l, s; ll p, q; int gcd (int A, int B) {If (B = 0) return a; else return gcd (B, A % B);} ll extend_gcd (int A, int B, ll & X, ll & Y) {ll T, ans; If (B = 0) {x = 1; y = 0; return a;} else {ans = extend_gcd (B, A % B, X, y); t = x; X = y; y = T-A/B * Y;} return ans;} int main () {scanf ("% d", & X, & Y, & M, & N, & L); X = x % L; y = Y % L; M = m % L; n = n % L; S = gcd (m-N, L); If (Y-x) % s! = 0) {printf ("impossible \ n");} else {extend_gcd (m-n, l, p, q); P = p * (Y-x) /s; L = L/s; If (L <0) L =-L; printf ("% d \ n", (P % L + l) % L );}}