码迷,mamicode.com
首页 > 其他好文 > 详细

poj 2115

时间:2019-07-10 01:24:49      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:允许   code   single   gcd   and   input   ted   typedef   ros   

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
这道题一开始我认为不就是减一下除就行了,结果a,c,b大小不确定,是允许溢出的!!!,所以这就比较恶心了,不过恰好是一个extgcd,只不过模的数变成了2^k,对了,我还因为少些一个<<= wa了半个小时,真实
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
ll extgcd(ll a,ll b,ll &x,ll &y)
{
    ll d=a;
    if(b!=0)
    {
        d=extgcd(b,a%b,y,x);
        y-=(a/b)*x;
    }
    else
    {
        x=1;y=0;
    }
    return d;
}
int main()
{
    ll a,b,c,k;
    while(cin>>a>>b>>c>>k)
    {
        if(a==0&&b==0&&c==0&&k==0)
        break;
        else
        {
            ll l=1;
            l<<=k;
            ll x,y;
            ll realgcd=extgcd(c,l,x,y);
            if((b-a)%realgcd)
            {
                printf("FOREVER\n");
                continue;
            }
            else
            {
                ll kk=(b-a)/realgcd;
                x*=kk;
                l/=realgcd;
                x=(x%l+l)%l;
                printf("%lld\n",x);

            }
        }
    }
}

 

poj 2115

标签:允许   code   single   gcd   and   input   ted   typedef   ros   

原文地址:https://www.cnblogs.com/coolwx/p/11161371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!