POJ_2115_C Looooops

C Looooops
Time Limit: 1000MS
Memory Limit: 65536K
Total Submissions: 27655
Accepted: 7893

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 < 2k) modulo 2k

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

Source

CTU Open 2004


  • 题目给出A,B,C,M,让计算循环次数
  • 其实就是同余方程:
  • A + C*x = B (mod M);
  • 化简下:
  • C*x = (B-A) (mod M);
  • 无解就是forever,有解就是答案
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
typedef long long           LL ;
typedef unsigned long long ULL ;
const int    maxn = 1000 + 10  ;
const int    inf  = 0x3f3f3f3f ;
const int    npos = -1         ;
const int    mod  = 1e9 + 7    ;
const int    mxx  = 100 + 5    ;
const double eps  = 1e-6       ;


LL extgcd(LL a, LL b, LL &x, LL &y){
	if(0==b){
		x=1;
		y=0;
		return a;
	}else{
		LL r=extgcd(b,a%b,y,x);
		y-=x*(a/b);
		return r;
	}
}
LL mod_equ(LL a, LL b, LL n){
	LL x, y;
	LL d=extgcd(a,n,x,y);
	if(0==b%d){
		x=(x%n + n)%n;
		return x*(b/d)%(n/d);
	}else{
		return -1;
	}
}
LL M, A, B, C, K, ans;
int main(){
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	while(~scanf("%lld %lld %lld %lld",&A,&B,&C,&K) && (A+B+C+K)){
		M=(LL)1<<K;
		if(A==B){
			puts("0");
		}else{
			ans=mod_equ(C,((B-A)%M + M)%M,M);
			if(-1==ans)
				puts("FOREVER");
			else
				printf("%lld\n",ans);
		}
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章