C Looooops
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 26411 | Accepted: 7516 |
Description
A Compiler Mystery: We are given a C-language style for loop of type
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.
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.
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
Source
题意:for(i=A; i!=B; i+=C)
{
i = i%(2^k);
}问这个东西要循环多少次。
思路:
设循环t次:
(A+t*C) % 2^k = B
A+t*C = n*2^k + B
又是扩展欧几里得的ax + by = c
其中a = C,b = -2^k,c = B-A,求最小的t解即可。
# include <stdio.h>
# include <stdlib.h>
# define LL long long
LL A, B, C, K;
LL x, y, a, b, c, d;
LL ex_gcd(LL a, LL b)
{
LL t;
if(b == 0)
{
x = 1;
y = 0;
return a;
}
d = ex_gcd(b, a%b);
t = x;
x = y;
y = t-(a/b)*y;
return d;
}
int main()
{
while(~scanf("%lld%lld%lld%lld",&A,&B,&C,&K),A+B+C+K)
{
a = C;
b = -((LL)1<<K);//移位记得要转换类型。
c = B-A;
d = ex_gcd(a, b);
if(c % d != 0)
{
puts("FOREVER");
continue;
}
x *= c/d;
y *= c/d;
if(x > 0)//b/d肯定是负数,但x可能是负数,故分成两类讨论,以后在改优雅一点。
printf("%lld\n",x%(-b/d));
else
{
LL k = llabs(x)*d/b;
k = x + b*k/d;
if(k < 0)
k += llabs(b/d);
printf("%lld\n",k);
}
}
return 0;
}