C Looooops
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 23637 |
|
Accepted: 6528 |
Description
A Compiler mystery:we is given a c-language style for loop of type
for (variable = A; variable! = B; variable + C)
Statement
i.e., a loop which starts by setting variable to value A and while variable are not equal to B, repeats statement followed By increasing the variable by C. We want to know what many times does the statement get executed for particular values of A, B and C, assuming this all Arit Hmetics is calculated in a k-bit unsigned integer type (with values 0 <= x < 2k) modulo 2k.
Input
The input consists of several instances. Each instance are described by a A, a and four integers a, B, C and K separated by a single space. The integer k (1 <= k <=) is the number of bits of the control variable of the loop and A, B, C (0 <= A, B, c < 2k) is the parameters of the loop.
The input is finished by a line containing four zeros.
Output
The output consists of several lines corresponding to the instances on the input. The i-th line contains either the number of executions of the statement in the I-th instance (a single integer number) or The word FOREVER if the loop does not terminate.
Sample Input
3 3 2 163 7 2 167 3 2 163 4 2 160 0 0 0
Sample Output
0232766FOREVER
Source
CTU Open 2004
Analysis: a+cx%2^k=b, solving the smallest xa-b+cx%2^k=0cx= (b-a)%2^k @1: A typical congruence equation, solved by ext_gcd cx+ (2^k) y= (b-a) when and only if GCD (c,2^k) | (b-a), the equation has a solution. We obtained the solution b-a of cx+ (2^k) Y=GCD (X,Y,GCD) by EXT_GCD. The/gcd* of the two sides of the equation is B-a (@1). That is, x = x* (b-a)/gcd. Because we ask for the smallest x, we find the period of change of the x that meets the condition: t:= (2^k)/gcd. Then get the smallest x through (x%t+t)%t, don't ask me why, because I don't know why.
#include <iostream>#include<stdio.h>using namespacestd;Long LongPowLong Longk) { Long Longans=1; for(intI=0; i<k;i++) ans*=2; returnans;}Long LongEXT_GCD (Long LongALong LongBLong Long*x,Long Long*y) { if(b==0) { *x=1, *y=0; returnA; } Long LongR = EXT_GCD (b,a%b,x,y); Long Longt = *x; *x = *y; *y = t-a/b * *y; returnR;}intMain () {Long Longa,b,c,k; while(~SCANF ("%i64d%i64d%i64d%i64d",&a,&b,&c,&k)) {if((a+b+c+k) = =0) Break; Long Longx, y; Long Long_gcd_ = EXT_GCD (C,pow (k),&x,&y); if((b-a)%_gcd_) {printf ("forever\n"); Continue; } Long LongTmp_ans = x* (b-a)/_gcd_; Long LongT = Pow (k)/_gcd_;/*to summarize: B/GCD is Ax+by = K*GCD, x*k/gcd cycle*/ Long LongAns = (tmp_ans%t+t)%T; printf ("%i64d\n", ans); } return 0;}
View Code
POJ 2115 Looooops