poj 2115 C Looooops(推公式+扩展欧几里得模板)

时间:2023-03-10 01:42:16
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 <= x < 2k) modulo 2k.

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 ( <= k <= ) is the number of bits of the control variable of the loop and A, B, C ( <= A, B, C < 2k) 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


Sample Output


FOREVER

Source

解题思路:这道题和POJ1061(青蛙约会)一样,都是同余方程的求解,用到了拓展欧几里德算法。而本题题意明确,就是求解这个公式:(a+c*x)mod2^k=b ,求得x 的最小解。变形后可得:c*xmod2^k=b-a,即 c*x=(b-a)mod2^k; 这就是标准的同余方程。

注意:k <=32 ,而 2的 32次方超出整数范围,所以要用__int64或long long ,就不会出现runtime error了。

 #pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<bitset>
#include<map>
#include<vector>
#include<stdlib.h>
using namespace std;
#define max(a,b) (a) > (b) ? (a) : (b)
#define min(a,b) (a) < (b) ? (a) : (b)
#define ll long long
#define eps 1e-10
#define MOD 1000000007
#define N 1000000
#define inf 1e12
ll fac(ll m){
ll ans=;
for(ll i=;i<m;i++){
ans=ans*;
}
return ans;
}
ll e_gcd(ll a,ll b,ll &x,ll &y){
if(b==)
{
x=;
y=;
return a;
}
ll r=e_gcd(b,a%b,x,y);
ll t=x;
x=y;
y=t-a/b*y;
return r;
}
int main()
{
ll a,b,c,k;
while(scanf("%I64d%I64d%I64d%I64d",&a,&b,&c,&k)==){
if(a== && b== && c== && k==){
break;
}
ll x,y,r;
ll d=e_gcd(c,fac(k),x,y);
//printf("---%I64d %I64d %I64d\n",d,x,y);
if((b-a)%d!=){
printf("FOREVER\n");
}
else{
x=x*(b-a)/d;
r=fac(k)/d;
x=(x%r+r)%r;
printf("%I64d\n",x);
}
}
return ;
}