C Looooops

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 < 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

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+nC+m*2^k=B   (A+加了n次的C+取了多少次模的B==B)

在转化以下就是 nC+2^k*m=B-A;

就转化成了扩展欧几里得模板 其中 a=C,b=2^k,c=B-A,带入模板求最小正整数解就行了。

(还有就是前几次提交一直报runtime error,以为是除以了0,但最后把int 改成了Long Long 就过了,应该是数据溢出了吧,但应该是报WA啊, 有点懵 - -)

#include <iostream>
#include <cstdio>
using namespace std;
long long poww(long long a,long long b){
	long long ans=1;
	while(b!=0){
		if(b&1) ans=(ans*a);
		b>>=1;
		a=a*a;
	}
	return ans;
}
long long ex_gcd(long long a, long long b, long long &x, long long &y){
	if(b==0){
		x=1,y=0;
		return a;
	}
	long long p=ex_gcd(b,a%b,y,x);
	y-=a/b*x;
	return p;
}
long long cal(long long a,long long b,long long c){
	long long x,y;
	long long gcd=ex_gcd(a,b,x,y);
	if(c%gcd!=0) return -1;
	x*=c/gcd;
	b/=gcd;
	if(b<0) b=-b;
	long long ans=x%b;
	if(ans<=0) ans+=b;
	return ans;
}
int main()
{	long long A,B,C,k;
	while(cin>>A>>B>>C>>k)
	{
		if(A==0 && B==0 && C==0 && k==0)
		{
			break;
		}
		if(A==B){
			cout<<"0"<<endl;
			continue;
		}
		long long d=C;
		long long e=poww(2,k);
		long long f=B-A;
		if(cal(C,poww(2,k),B-A)!=-1)
		cout<<cal(d,e,f)<<endl;
		else cout<<"FOREVER"<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40941611/article/details/81270137