题目:
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 < 2k) modulo 2k.
思路:
乍一看以为是推公式的题,后来知道是扩展欧几里得。
先根据题意得出要解的方程:(A+Cx)%2^k=B;
可化为:(Cx)%(2^k)=B-A;
在化为:Cx%(2^k)=(B-A)%(2^k);
再化为:Cx+(2^k)*y=B-A;
即对应于求方程ax+by=n的一个整数解!直接上欧几里得模板套一下就出来了;
AC代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
using namespace std;
typedef long long ll;
ll A,B,C,a,b,c,k,ans;
void exgcd(ll a,ll b,ll &x,ll &y,ll &d){
if(!b){
x=1,y=0,d=a;
}
else{
exgcd(b,a%b,y,x,d);
y-=x*(a/b);
}
}
int main(){
while(cin>>A>>B>>C>>k){
if(A==0&&B==0&&C==0&&k==0) break;
a=C;
b=1LL<<k;
c=B-A;
ll x,y,d;
exgcd(a,b,x,y,d);
if(c%d==0){
ans=(c/d*x%(b/d)+b/d)%(b/d);
cout<<ans<<endl;
}
else{
puts("FOREVER");
}
}
return 0;
}