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.
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.
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.
3 3 2 16 3 7 2 16 7 3 2 16 3 4 2 16 0 0 0 0
0 2 32766 FOREVER
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
long long gcd(long long a, long long b)
{
return b == 0 ? a : gcd(b, a%b);
}
long long extendgcd(long long a, long long b, long long &x, long long &y)
{
if (b == 0)
{
x = 1;y = 0;
return a;
}
long long ret = extendgcd(b, a%b, x, y);
long long t = x;
x = y;
y = t - a / b*y;
return ret;
}
long long a, b, c, k;
long long muti[35];
int main()
{
muti[0] = 1;
for (int i = 1;i < 35;i++)
muti[i] = 2 * muti[i - 1];
while (1)
{
cin >> a >> b >> c >> k;
//scanf("%lld %lld %lld %lld", &a, &b, &c, &k);
if ((a == 0 && b == 0)&&(c==0&&k==0))
return 0;
long long mmod = muti[k];
long long gcd1 = gcd(mmod, c);
if ((b - a) % gcd1 != 0)
{
printf("FOREVER\n");
continue;
}
long long x;
long long y;
extendgcd(c / gcd1, mmod / gcd1, x, y);
x *= (b - a) / gcd1;
y *= (b - a) / gcd1;
long long stepa = mmod / gcd1;
//cout << x << endl;
//cout << stepa << endl;
long long stepb = c / gcd1;
if (b - a <= 0)
{
if (x <= 0)
{
x = (stepa-((-x) % stepa)) % stepa;
}
else
{
x = x%stepa;
}
}
else
{
long long pos = (b - a) % c==0? (b - a) /c: 1+(b - a) / c;
if (x <= pos)
{
x = pos+(stepa - (pos-x) % stepa) % stepa;
}
else
{
x = pos+(x-pos)%stepa;
}
}
//printf("%d\n", x);
cout << x << endl;
}
return 0;
}