POJ2115C Looooops
http://poj.org/problem?id=2115
k位储存特点,一旦溢出,那么就到第二个循环开始返回0重新计数。问题实际转化成a+cx=b(mod 2^k)跑多少圈能够重合。因为是k位无符号,所以直接就是2^k次方,0~2^k-1。刚好覆盖模的范围
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 typedef unsigned long long ll; 7 ll ex_gcd(ll a, ll b, ll &x,ll &y) 8 { 9 if(!b){x=1,y=0;return a;} 10 ll d=ex_gcd(b,a%b,x,y); 11 ll tmp=x; 12 x=y,y=tmp-a/b*y; 13 return d; 14 } 15 int main() 16 { 17 ll a,b,c,k,x,y; 18 while(~scanf("%llu%llu%llu%llu",&a,&b,&c,&k),(a+b+c+k)) 19 { 20 ll tmp=c;//k位无符号 21 c=b-a;a=tmp;b=(ll)1<<k; 22 ll d=ex_gcd(a,b,x,y); 23 ll t=b/d; 24 if(c%d!=0) cout<<"FOREVER\n"; 25 else 26 { 27 x=(x*c/d%t+t)%t; 28 cout< '\n'; 29 } 30 } 31 return 0; 32 }