/* (X * C + a) % (2 ^ K) = B → (x * C) % (2 ^ K) = B-A satisfies the theorem: inference 1: The equation Ax = B (mod n) has a solution for the unknown x. if and only when gcd (A, n) | B. Inference 2: The equation Ax = B (mod n) or there are d different solutions to the modulus n, where D = gcd (A, n), or no solution. Theorem 1: Set d = gcd (A, n). Assume that the integers x and y meet d = AX + by (for example, a group of solutions obtained by the extended Euclid algorithm ). If d | B, then the equation Ax = B (mod n) has a solution where x0 satisfies X0 = x * (B/d) mod n. In particular, let's set E = x0 + N, the minimum integer solution of the equation Ax = B (mod n) x1 = e Mod (N/d ), the maximum integer is x 2 = X1 + (D-1) * (N/d ). Theorem 2: assume that the equation Ax = B (mod n) has a solution, and x0 is any solution of the equation, then the equation has exactly d different solutions for model N (D = gcd (A, n), namely: xi = x0 + I * (N/d) mod n. */# Include <stdio. h >__ int64 ext_gcd (_ int64 A ,__ int64 B ,__ int64 & X ,__ int64 & Y) {If (B = 0) {x = 1; y = 0; return a;} _ int64 d = ext_gcd (B, A % B, x, y); _ int64 T = x; X = y; y = T-A/B * Y; return D ;}__ int64 modular_linear (_ int64 A ,__ int64 B ,__ int64 N) {_ int64 D, E, x, Y; D = ext_gcd (A, n, x, y); If (B % d) return-1; E = x * (B/d) % N + N; Return e % (n/d);} int main (void) {_ int64 D, a, B, c, K; while (scanf ("% LLD", & A, & B, & C, & K), a | B | c | K) {d = modular_linear (C, B-A, (_ int64) 1 <k); If (D =-1) puts ("forever "); else printf ("% LLD \ n", d);} return 0 ;}