zhber 有好多做过的题没写下来，如果我还能记得就补吧
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 particular 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 16
3 7 2 16
7 3 2 16
3 4 2 16
0 0 0 0


Sample Output

0
2
32766
FOREVER  1 #include<cstdio>
2 #include<iostream>
3 #include<cstring>
4 #define LL long long
5 using namespace std;
7 {
8     LL x=0,f=1;char ch=getchar();
9     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
10     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
11     return x*f;
12 }
13 LL A,B,C,D,k;
14 inline LL exgcd(LL a,LL b,LL &x,LL &y)
15 {
16     if(!b){x=1;y=0;return a;}
17     LL gcd=exgcd(b,a%b,x,y);
18     LL t=x;x=y;y=t-a/b*y;
19     return gcd;
20 }
21 inline LL calc(LL a,LL b,LL c)//Ax==B(mod C)
22 {
23     LL x,y;
24     LL tt=exgcd(a,c,x,y);
25     if (b%tt!=0)return -1;
26     x=x*b/tt;
27     LL ss=c/tt;
28     x=(x%ss+ss)%ss;
29     return x;
30 }
31 int main()
32 {
33     while (~scanf("%lld%lld%lld%lld",&A,&B,&C,&k)&&(A+B+C+k))
34     {
35         D=1ll<<k;
36         if (B==A){puts("0");continue;}
37         B=(B-A+D)%D;
38         LL ans=calc(C,B,D);
39         if (ans==-1)puts("FOREVER");
40         else printf("%lld\n",ans);
41     }
42 }
poj 2115

——by zhber，转载请注明来源
posted on 2017-08-04 15:42  zhber  阅读(181)  评论(0编辑  收藏  举报