C Looooops
Time Limit: 1000MS | | Memory Limit: 65536K |
Total Submissions: 20725 | | Accepted: 5598 |
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
0
2
32766
FOREVER
//思路
由题意知:a+c*x=b; 则:c*x=b-a; 又因为他们有一个范围,2^k;(相当于有2^k个人,围成一圈,每人有一个编号,转到最大编号后,又从1开始了)。 所以:公式可以完善为:c*x=(b-a)%(1<<k) ; 由此公式可推出方程: c*x+(b-a)*y=gcd(c,(b-a)); 代换一下可得: aa*x+bb*y=(b-a);
其中 aa=c;bb=1<<k; 然后求出x就行了。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define ll __int64
using namespace std;
ll gcd(ll a,ll b,ll &x,ll &y)
{
if(!b)
{
x=1;
y=0;
return a;
}
ll ans=gcd(b,a%b,x,y);
ll tmp=x;
x=y;
y=tmp-a/b*y;
return ans;
}
int main()
{
ll a,b,n;
ll A,B,C,K;
while(scanf("%I64d%I64d%I64d%I64d",&A,&B,&C,&K),A|B|C|K)
{
a=C;
b=B-A;
n=(ll)1<<K;
ll x,y;
ll d=gcd(a,n,x,y);
if(b%d!=0)
printf("FOREVER\n");
else
{
x=(x*(b/d))%n;
x=(x%(n/d)+n/d)%(n/d);
printf("%I64d\n",x);
}
}
return 0;
}
//套模板
#include<stdio.h>
#include<string.h>
#define ll __int64
ll gcd(ll a,ll b,ll &x,ll &y)
{
if(!b)
{
x=1;
y=0;
return a;
}
ll ans=gcd(b,a%b,x,y);
ll tmp=x;
x=y;
y=tmp-a/b*y;
return ans;
}
ll val(ll a,ll b,ll c)
{
ll x,y;
ll d=gcd(a,b,x,y);
if(c%d!=0)
return -1;
x*=c/d;
b/=d;
if(b<0)
b=-b;
ll ans=x%b;
if(ans<=0)
ans+=b;
return ans;
}
int main()
{
ll A,B,C,k;
while(scanf("%I64d%I64d%I64d%I64d",&A,&B,&C,&k),A|B|C|k)
{
if(A==B)
printf("0\n");
else
{
ll a=C;
ll b=(ll)1<<k;
ll n=B-A;
ll cnt=val(a,b,n);
if(cnt==-1)
printf("FOREVER\n");
else
printf("%I64d\n",cnt);
}
}
return 0;
}