C looooops
Time limit:1000 ms |
|
Memory limit:65536 K |
Total submissions:17981 |
|
Accepted:4694 |
Description
A compiler mystery: we are 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 is not equal to B, repeats statement followed by increasing the variable by C. we want to know how many times does the statement get executed for particle values of A, B and C, assuming that all arithmetics is calculated in a K-bit unsigned integer type (with values 0 <= x <2 k) modulo 2 K.
Input
The input consists of several instances. each instance is described by a single line with four integers A, B, C, K separated by a single space. the integer k (1 <= k <= 32) is the number of bits of the control variable of the loop and A, B, C (0 <= A, B, c <2 k) are 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
Or extend Euclidean...
There is a for loop Statement (INT I = A; I! = B; I = (I + C) % 2 ^ K) sta; Given A, B, C, K; ask when the loop ends;
Set the cycle to terminate X times, you can get (a + x * C) % 2 ^ K = B; that is, a + x * C-B = y * 2 ^ K; (y =, 2 ...)
Sort C * X-2 ^ K * Y = B-A; make a = C; B =-2 ^ K; C = B-A;
Obtain AX + by = C;
The preceding solution means that the loop can be terminated, and the minimum integer solution of X is the number of cycles.
#include <iostream>#include <cstring>#include <cstdio>#include <cctype>#include <cstdlib>#include <algorithm>#include <set>#include <vector>#include <string>#include <cmath>#include <map>#include <queue>using namespace std;#define LL long longLL gcd(LL a,LL b){ if(b==0)return a; return gcd(b,a%b);}void exgcd(LL a,LL b,LL &x,LL &y){ if(b==0) { x=1; y=0; return ; } exgcd(b,a%b,y,x); y-=a/b*x;}int main(){ LL A,B,C,k,x,y; while(cin>>A>>B>>C>>k){ if(!A&&!B&&!C&&!k)break; LL a=C; LL b=-pow(2LL,k); LL c=B-A; LL r=gcd(a,b); if(c%r) { puts("FOREVER"); continue; } a/=r;b/=r;c/=r; exgcd(a,b,x,y); if(b<0)b=-b; x*=c; cout<<(x%b+b)%b<<endl; } return 0;}
Poj 2115-c looooops (Extended Euclidean)