poj 2115
Posted coolwx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 2115相关的知识,希望对你有一定的参考价值。
Compiler Mystery: We are given a C-language style for loop of type
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.
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.
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的主要内容,如果未能解决你的问题,请参考以下文章