您的位置:首页 > 运维架构

POJ 2115 C Looooops(扩展欧几里得)

2015-08-10 18:53 363 查看
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 < 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.

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+CX)=B(mod M)(M=2^K)
分析:稍微化简下我们知道ax+by=c(mod M) a=C,B=M,c=(B-A)
这样就和青蛙那道一样了
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<string>
#include<iostream>
#include<queue>
#include<cmath>
#include<map>
#include<stack>
#include<set>
using namespace std;
#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )
#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )
#define CLEAR( a , x ) memset ( a , x , sizeof a )
const int INF=0x3f3f3f3f;
typedef long long LL;
const int maxn=1e6+100;
LL A,B,C,K;
LL bin[35];
void init()
{
    bin[0]=1;
    for(int i=1;i<=32;i++)
        bin[i]=bin[i-1]*2;
}
void exgcd(LL a,LL b,LL &xx,LL &yy)
{
    if(b==0)
    {
        xx=1;yy=0;
        return;
    }
    exgcd(b,a%b,xx,yy);
    LL t=xx;xx=yy;yy=t-a/b*yy;
    return;

}
int main()
{
   init();
   while(cin>>A>>B>>C>>K)
   {
       if(!A&&!B&&!C&&!K)
          break;
      LL temp=B-A;
      A=C;B=bin[K];
      C=temp;
      while(C<0)
          C+=bin[K];
       LL d=__gcd(A,B);
       if(C%d)
       {
           puts("FOREVER");
           continue;
       }
       A/=d;B/=d;C/=d;
       LL xx,yy;
       exgcd(A,B,xx,yy);
       xx=xx*C%B;
       while(xx<0)
        xx+=B;
       cout<<xx<<endl;
   }
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: