poj 2115 C Looooops (扩展欧几里得算法)
题意: 问 循环for ( int i = a ; i !=b; i+=c)在% (2^k)的意义下循环了多少次。
思路:
一般的思路是:
列方程...
化成扩展欧几里得算法的形式。。。
根据裴蜀定理判断解是否存在...
然后用对用扩展欧几里得算法求出的X,Y按照题目要求调整。
1/* ***********************************************
2Author :111qqz
3Created Time :Thu 13 Oct 2016 03:57:06 PM CST
4File Name :code/poj/2115.cpp
5************************************************ */
6#include <cstdio>
7#include <cstring>
8#include <iostream>
9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <set>
13#include <map>
14#include <string>
15#include <cmath>
16#include <cstdlib>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31LL a,b,c,k;
32LL exgcd(LL a,LL b,LL &x,LL &y)
33{
34 if (b==0)
35 {
36 x = 1;
37 y = 0;
38 return a;
39 }
40 LL ret = exgcd(b,a%b,x,y);
41 LL tmp = x;
42 x = y;
43 y = tmp - a/b*y;
44 return ret;
45}
46int main()
47{
48 #ifndef ONLINE_JUDGE
49 freopen("code/in.txt","r",stdin);
50 #endif
51 while (~scanf("%lld%lld%lld%lld",&a,&b,&c,&k))
52 {
53 if (a==0&&b==0&&c==0&&k==0) break;
54 k = 1LL<<k;
55 LL X,Y,GCD;
56 GCD = exgcd(c,k,X,Y);
57 if ((b-a)%GCD)
58 {
59 puts("FOREVER");
60 continue;
61 }
62 else
63 {
64 X = X * ((b-a)/GCD);
65 LL gx = k/GCD;
66 X = (X % gx + gx) % gx;
67 printf("%lld\n",X);
68 }
69 }
70 #ifndef ONLINE_JUDGE
71 fclose(stdin);
72 #endif
73 return 0;
74}