题目如下:
思路 or 题解:
抽象出数学公式:
a
+
k
∗
c
≡
b
(
m
o
d
1
<
<
k
)
a + k * c \equiv b (mod\ 1 << k)
a+k∗c≡b(mod 1<<k)
等价:
x
∗
c
−
y
∗
(
1
<
<
k
)
=
b
−
a
x * c - y * (1 << k) = b - a
x∗c−y∗(1<<k)=b−a
用扩展欧几里得算法求解即可
答案就是:
x
0
%
1
<
<
k
g
c
d
x_0\ \%\ \frac{1<<k}{gcd}
x0 % gcd1<<k
AC 代码如下:
#define int long long
#define ll long long
int a, b, c, k;
int exgcd(int a, int b, int &x, int &y)
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
int d = exgcd(b, a % b, y, x);
y = y - a / b * x;
return d;
}
void solve()
{
int t = 1ll << k;
int x, y;
int d = exgcd(c, t, x, y);
if ((b - a) % d)
{
cout << "FOREVER\n";
return;
}
else
{
x = x * (b - a) / d;
t /= d;
cout << (x % t + t) % t << '\n';
}
}
signed main()
{
buff;
while (cin >> a >> b >> c >> k, a || b || c || k)
solve();
}