[Poj 2115] C Looooops [Extended Euclidean] [modulus linear equation]

Source: Internet
Author: User
Tags modulus

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 );}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.