POJ 2115-C Looooops(扩展欧几里德)

来源:互联网 发布:上海房产成交数据 编辑:程序博客网 时间:2024/05/16 19:52
C Looooops
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 17981 Accepted: 4694

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 163 7 2 167 3 2 163 4 2 160 0 0 0

Sample Output

0232766FOREVER
还是扩展欧几里德。。。
题意 :有一条for循环语句 (int i=A;i!=B;i=(i+C)%2^k) sta; 给定A,B,C,k;问循环什么时候终止;
设循环x次终止, 则可得 (A+x*C)%2^k=B;即 A+x*C-B=y*2^k;(y=0,1,2...)
整理  C*x-2^k*y=B-A;令a=C;b=-2^k;c=B-A;
得  ax+by=c;
上式有解即意味着循环可以终止,x的最小整数解即为循环次数。
#include <iostream>#include <cstring>#include <cstdio>#include <cctype>#include <cstdlib>#include <algorithm>#include <set>#include <vector>#include <string>#include <cmath>#include <map>#include <queue>using namespace std;#define LL long longLL gcd(LL a,LL b){    if(b==0)return a;    return gcd(b,a%b);}void exgcd(LL a,LL b,LL &x,LL &y){    if(b==0)    {        x=1;        y=0;        return ;    }    exgcd(b,a%b,y,x);    y-=a/b*x;}int main(){    LL A,B,C,k,x,y;    while(cin>>A>>B>>C>>k){    if(!A&&!B&&!C&&!k)break;    LL a=C;    LL b=-pow(2LL,k);    LL c=B-A;    LL r=gcd(a,b);    if(c%r)    {        puts("FOREVER");        continue;    }    a/=r;b/=r;c/=r;    exgcd(a,b,x,y);    if(b<0)b=-b;    x*=c;    cout<<(x%b+b)%b<<endl;  }    return 0;}


2 0
原创粉丝点击