天天看点

POJ 2115 C Looooops

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 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

2

32766

FOREVER

#include<set>
#include<map>
#include<ctime>
#include<cmath>
#include<stack>
#include<queue>
#include<bitset>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define rep(i,j,k) for (int i = j; i <= k; i++)
#define per(i,j,k) for (int i = j; i >= k; i--)
#define loop(i,j,k) for (int i = j;i != -1; i = k[i])
#define lson x << 1, l, mid
#define rson x << 1 | 1, mid + 1, r
#define fi first
#define se second
#define mp(i,j) make_pair(i,j)
#define pii pair<string,string>
using namespace std;
typedef long long LL;
const int low(int x) { return x&-x; }
const double eps = 1e-8;
const int INF = 0x7FFFFFFF;
const int mod = 9973;
const int N = 5e3 + 10;
const int read()
{
  char ch = getchar();
  while (ch<'0' || ch>'9') ch = getchar();
  int x = ch - '0';
  while ((ch = getchar()) >= '0'&&ch <= '9') x = x * 10 + ch - '0';
  return x;
}
LL a, b, c, d;

LL exgcd(LL a, LL b, LL &x, LL &y)
{
  if (!b) { x = 1, y = 0; return a; }
  LL g = exgcd(b, a%b, x, y);
  LL z = x - a / b * y;
  x = y;  y = z;  return g;
}

int main()
{
  while (scanf("%lld%lld%lld%lld%", &a, &b, &c, &d) != EOF)
  {
    if (a + b + c + d == 0) break;
    LL x, y, g = exgcd(c, -1LL << d, x, y);
    if ((b - a) % g) printf("FOREVER\n");
    else
    {
      LL ans = (b - a) / g * x, m = (1LL << d) / g;
      if (m < 0) m = -m;
      printf("%lld\n", (ans%m + m) % m);
    }
  }
  return 0;
}