「POJ2115」C Looooops
Description
A 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 < 2k) modulo 2k.
1 2 3 |
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
1 2 3 4 5 |
3 3 2 16 3 7 2 16 7 3 2 16 3 4 2 16 0 0 0 0 |
Sample Output
1 2 3 4 |
0 2 32766 FOREVER |
题解
A+nC-B=m2^k
nC-m2^k=B-A
然后扩展gcd
注意b=1<<32要改成1LL<<32似乎
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include<iostream> #include<cstdio> #define ll long long using namespace std; ll gcd(ll a,ll b) {return b==0?a: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,x,y); ll t=x;x=y;y=t-a/b*y; } int main() { ll A,B,C,k; ll x,y,a,b,c,t; while(scanf("%lld%lld%lld%lld",&A,&B,&C,&k)) { if(!A&&!B&&!C&&!k)return 0; a=C;b=1;c=B-A; for(int i=1;i<=k;i++) b=b*2; t=gcd(a,b); if(c%t!=0){printf("FOREVER\n");continue;} a/=t;b/=t;c/=t; exgcd(a,b,x,y); x=((c*x)%b+b)%b; if(!x)x+=b; printf("%lld\n",x); } } |
标程错了吧?
应该是if(x<0)x+=b不是if(!x)
不对,if()x+=b这句话根本不需要。。