标签:
题目:
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
题意倒是很简单,就是求满足c*x-2^k*y=b-a的所有(x,y)中,x的最小非负值。
代码:
#include<iostream> #include<stdio.h> using namespace std; long long x, y; long long gcd(long long a, long long b) { if (a == 0 || b == 0) { x = (b == 0); y = (a == 0); return a + b; } long long r; if (a < 0) { r = gcd(-a, b); x *= -1; return r; } if (b < 0) { r = gcd(a, -b); y *= -1; return r; } if (a >= b)r = gcd(a%b, b); else r = gcd(a, b%a); y -= a / b*x; x -= b / a*y; return r; } int main() { long long a, b, c, k, con = 1; while (cin >> a >> b >> c >> k) { if (k == 0)break; b -= a; k = (con << k); if (b == 0)cout << 0; else { long long g = gcd(c, -k); if (b%g)cout << "FOREVER"; else cout << (x*b / g%k + k) % (k / g); } cout << endl; } return 0; }
核心函数是拓展欧几里得函数gcd,不会的请点击打开我的博客
标签:
原文地址:http://blog.csdn.net/nameofcsdn/article/details/52252662