Question:
For (variable = A; variable! = B; variable + = C)
Statement;
Given A, B, C, and k (k indicates that the variable is an unsigned integer on A k-bit machine), the number of cycles is determined and the output "FOREVER" cannot be terminated ".
Ideas:
Need to solve (A + x * C) % mod = B
After deformation, C * x + mod * y = B-A = gcd (C, mod) * [(B-A)/gcd (C, mod)]
To use the Extended Euclidean theorem, C * x + mod * y = gcd (C, mod) is required)
A = C, B = mod
Modulus linear equation
Note that after the special solution obtained by the modulus linear equation is converted to a positive number, it is necessary to modulo B/gcd (a, B) [instead of B] ***. The explanation is as follows:
The meaning of the obtained solution is "number of steps", so we need to model the cycle corresponding to the number of steps ".
# Include <cstdio> using namespace std; typedef long ll; ll Extended_Euclid (ll a, ll B, ll & x, ll & y) {if (! B) {x = 1; y = 0; // return a;} ll r = Extended_Euclid (B, a % B, x, y); ll t = x; x = y; y = t-a/B * y; return r;} ll Modular_Linear_Equation (ll a, ll B, ll n) {ll x, y, e; ll d = Extended_Euclid (a, n, x, y); if (B % d) return-1; e = x * B/d % n + n; // convert to a positive number. First, modulo and return e % (n/d ); // ***} int main () {ll a, B, c, ans; int k; while (scanf ("% lld % d ", & a, & B, & c, & k) & (a + B + c + k) {ans = Modular_Linear_Equation (c, B-a, (ll) 1) <k); if (ans =-1) puts ("FOREVER"); else printf ("% lld \ n", ans );}}