题意
传送门 POJ 2115
题解
求满足如下方程的 x x x 最小正值,拓展欧几里德算法即可
C x + 2 k y = B − A Cx+2^ky=B-A Cx+2ky=B−A
要特殊处理 A , B , C A,B,C A,B,C 为 0 0 0 的情况
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
typedef long long ll;
ll A, B, C, k;
ll extgcd(ll a, ll b, ll &x, ll &y)
{
ll d = a;
if (b != 0)
{
d = extgcd(b, a % b, y, x);
y -= (a / b) * x;
}
else
{
x = 1, y = 0;
}
return d;
}
int main()
{
while (~scanf("%lld%lld%lld%lld", &A, &B, &C, &k) && (A | B | C | k))
{
if (A == B)
{
printf("0\n");
continue;
}
if (C == 0)
{
printf("FOREVER\n");
continue;
}
ll a = C, b = (ll)1 << k, c = B - A;
ll x, y;
ll gcd = extgcd(a, b, x, y);
if (c % gcd != 0)
{
printf("FOREVER\n");
}
else
{
ll mod = b / gcd;
x *= c / gcd;
x = (x % mod + mod) % mod;
printf("%lld\n", x);
}
}
return 0;
}