C looooops (POJ 2115)

Source: Internet
Author: User

Approximate test instructions:

For C's for (i=a; i!=b; I +=c) loop, ask how many loops in the K-bit storage system will end.

If the end is within a finite number of times, the output cycle times.

Otherwise the output is dead loop.

Problem Solving Ideas:

Test instructions is not difficult to understand, but the use of K-bit storage system data characteristics to cycle.

For example , the int is 16 bits, then int can save 2^16 data, that is, the maximum number is 65535 (the default is unsigned),

When the loop causes I to exceed 65535, I will return 0 to start counting again

such as i=65534, when i+=3,i=1

is actually i= (65534+3)% (2^16) =1

With these ideas, it is easy to get the equation for a set of data to be looped through X-times:

x=[(b-a+2^k)%2^k]/C

That is cx= (b-a) (mod 2^k) This equation is a modal equation, the subject is to find the value of x.

//note the formula that finally changes the x to the smallest positive integer#include <cstdio>#include<iostream>#definell Long Longusing namespacestd;ll a,b,c,k;ll e_gcd (ll a,ll b,ll&x,ll &y) {    if(b==0) {x=1; y=0; returnA; } ll R=E_GCD (b,a%b,x,y); ll T=x;x=y;y=t-a/b*y; returnR;}intMain () { while(1) {cin>>A>>B>>C>>J; if(a==0&&b==0&&c==0&&k==0) Break; if(a==B) {printf ("0\n"); Continue; } ll a=c,b=1ll<<k,c=b-A,x,y; ll GCD=E_GCD (a,b,x,y); if(c%gcd) {printf ("forever\n"); Continue; } x=x*c/GCD; X= (x (B/GCD) + (B/GCD))% (b/GCD); cout<<x<<Endl; }}
View Code

C looooops (POJ 2115)

Related Article

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.