今天困成狗,明天又要跑一千米,真*&*(&#)(&*(^&*%#%
题意:
for (variable = A; variable != B; variable += C)对这个语句,计算它需要执行多少次,或者输出FOREVER,变量为长度为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.
真是跪成狗,果然数学还是做的太少了。
首先列出同余方程c*x=b-a(mod 2^k)
然后跟按定义求乘法逆元一样,用扩展欧基里德解x:ex_gcd(c,mod,x,y),y无用
然后是扩展欧基里德之后对x的调整,不管等式右边的常数最终选几,x的最小调动幅度是mod / gcd(c,mod),列等式就可以看出这一点,BTW,y的最小调动幅度是c / gcd(c,mod),由于算法保证|x|+|y|最小,所以只需要调整一次就可以,然后我调整的时候第一次没取模就WA了也是醉
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
long long ex_gcd(long long m,long long n,long long& x,long long& y){
if(!n){
x=1;
y=0;
return m;
}
int ret=ex_gcd(n,m%n,x,y);
int tem=x;
x=y;
y=tem-m/n*y;
return ret;
}
long long a,b,c,k;
int main(){
while(scanf("%lld%lld%lld%lld",&a,&b,&c,&k)!=EOF){
if(!a&&!b&&!c&&!k) break;
if(!c){
if(a==b) puts("0");
else puts("FOREVER");
continue;
}
long long mod=(1LL<<k);
long long x,n;
long long tem=ex_gcd(c,mod,x,n);
long long d=(b-a+mod)%mod;
if(d%tem){
puts("FOREVER");
continue;
}
x=x*(d/tem);
x=(x%(mod/tem)+mod/tem)%(mod/tem);
printf("%lld\n",x);
}
return 0;
}