2115

/*
	mod = 2^k;
	A+C*k === B  (mod mod)
	
	A+C*x - B = mod*y;
	C*x - mod*y = B-A;
	求x
	a = C;
	b = -mod;
	c = B-A;

*/

// include file
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <ctime>

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <bitset>

#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <list>
#include <functional>

using namespace std;

// typedef
typedef __int64 LL;

// 
#define read freopen("in.txt","r",stdin)
#define write freopen("out.txt","w",stdout)

#define Z(a,b) ((a)<<(b))
#define Y(a,b) ((a)>>(b))

const double eps = 1e-6;
const double INFf = 1e100;
const int INFi = 1000000000;
const LL INFll = (LL)1<<62;
const double Pi = acos(-1.0);

template<class T> inline T sqr(T a){return a*a;}
template<class T> inline T TMAX(T x,T y)
{
	if(x>y) return x;
	return y;
}
template<class T> inline T TMIN(T x,T y)
{
	if(x<y) return x;
	return y;
}
template<class T> inline T MMAX(T x,T y,T z)
{
	return TMAX(TMAX(x,y),z);
}
template<class T> inline T MMIN(T x,T y,T z)
{
	return TMIN(TMIN(x,y),z);
}
template<class T> inline void SWAP(T &x,T &y)
{
	T t = x;
	x = y;
	y = t;
}


// code begin
LL A,B,C,k,a,b,c,d;

LL gcd(LL m,LL n)
{
	if(n==0) return m;
	return gcd(n,m%n);
}

LL extGcd(LL a1,LL b1,LL &x,LL &y)
{
	if(b1==0)
	{
		x = 1;
		y = 0;
		return a1;
	}
	LL r = extGcd(b1,a1%b1,x,y);
	LL t = x;
	x = y;
	y = t-a1/b1*y;
	return r;
}

int main()
{
	read;
	write;
	while(scanf("%I64d %I64d %I64d %I64d",&A,&B,&C,&k)==4)
	{
		if(A+B+C+k==0) break;
		k = ((LL)1<<k);
		a = C;
		b = -k;
		c = B-A;
		d = gcd(a,b);
		if(c%d!=0)
		{
			printf("FOREVER\n");	
		}
		else
		{
			a/=d;
			b/=d;
			c/=d;
			LL x,y;
			extGcd(a,b,x,y);
			x*=c;
			x%=b;
			if(x<0) x+= (b<0?-b:b);
			printf("%I64d\n",x);
		}
	}
	return 0;
}
posted @ 2011-04-29 23:31  AC2012  阅读(211)  评论(0编辑  收藏  举报