C Looooops
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 28070 | Accepted: 8009 |
Description
A Compiler Mystery: We are given a C-language style for loop of type
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.
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.
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
Source
题意:给出一个k进制下的数a,每次循环+c,求到b所需的循环次数。当加到大于1<<k时,便从0开始了。
题解:(a+c*x)%mod=b(mod=(1<<k)),变形为a+c*x=mod*y+b,移项c*x+mod*y=b-a。所以就转化为求解不定方程的解也就是这个最小x。根据扩展欧几里德,不定方程有解当且仅当(b-a)|gcd(c,mod)。所以无解就是FOREVER,有解求出最小x即可。这里作为模板。
代码:
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<string>
#include<bitset>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<iomanip>
#include<iostream>
#define debug cout<<"aaa"<<endl
#define mem(a,b) memset(a,b,sizeof(a))
#define LL long long
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define MIN_INT (-2147483647-1)
#define MAX_INT 2147483647
#define MAX_LL 9223372036854775807i64
#define MIN_LL (-9223372036854775807i64-1)
using namespace std;
const int N = 100000 + 5;
const int mod = 1000000000 + 7;
LL exgcd(LL a,LL b,LL &x,LL &y){//扩展欧几里德算法模板
if(b==0){
x=1;
y=0;
return a;
}
LL r=exgcd(b,a%b,x,y);
LL t=x;
x=y;
y=t-a/b*y;
return r;
}
int main(){
LL a,b,c,k,gcd,x,y;
while(~scanf("%lld%lld%lld%lld",&a,&b,&c,&k)){
if(a==0&&b==0&&c==0&&k==0){
break;
}
b-=a;
k=(LL)1<<k;
gcd=exgcd(c,k,x,y);
if(b%gcd!=0){//无解
puts("FOREVER");
continue;
}
x=x*(b/gcd);
k/=gcd;
x=(x%k+k)%k;
printf("%lld\n",x);
}
return 0;
}