标签:des style color os io ar strong for art
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 17981 | Accepted: 4694 |
Description
for (variable = A; variable != B; variable += C) statement;
Input
Output
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
还是扩展欧几里德。。。
题意 :有一条for循环语句 (int i=A;i!=B;i=(i+C)%2^k) sta; 给定A,B,C,k;问循环什么时候终止;
设循环x次终止, 则可得 (A+x*C)%2^k=B;即 A+x*C-B=y*2^k;(y=0,1,2...)
整理 C*x-2^k*y=B-A;令a=C;b=-2^k;c=B-A;
得 ax+by=c;
上式有解即意味着循环可以终止,x的最小整数解即为循环次数。
#include <iostream> #include <cstring> #include <cstdio> #include <cctype> #include <cstdlib> #include <algorithm> #include <set> #include <vector> #include <string> #include <cmath> #include <map> #include <queue> using namespace std; #define LL long long LL gcd(LL a,LL b) { if(b==0)return a; return 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,y,x); y-=a/b*x; } int main() { LL A,B,C,k,x,y; while(cin>>A>>B>>C>>k){ if(!A&&!B&&!C&&!k)break; LL a=C; LL b=-pow(2LL,k); LL c=B-A; LL r=gcd(a,b); if(c%r) { puts("FOREVER"); continue; } a/=r;b/=r;c/=r; exgcd(a,b,x,y); if(b<0)b=-b; x*=c; cout<<(x%b+b)%b<<endl; } return 0; }
标签:des style color os io ar strong for art
原文地址:http://blog.csdn.net/qq_16255321/article/details/39055129