You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
29 lines
793 B
C++
29 lines
793 B
C++
#define _CRT_SECURE_NO_WARNINGS
|
|
#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING
|
|
#include <cassert>
|
|
#include <cstdio>
|
|
using namespace std;
|
|
typedef long long ll;
|
|
void exgcd(ll a, ll b, ll &d, ll &x, ll &y)
|
|
{
|
|
b == 0 ? (x = 1, y = 0, d = a) : (exgcd(b, a % b, d, y, x), y -= x * (a / b));
|
|
}
|
|
int main()
|
|
{
|
|
ll a, b, c, k;
|
|
while (scanf("%lld%lld%lld%lld", &a, &b, &c, &k), a | b | c | k)
|
|
{
|
|
ll mask = (1ll << k) - 1;
|
|
ll dif = (b + (1ll << k) - a) & mask;
|
|
ll _g, x, y;
|
|
exgcd(c, 1ll << k, _g, x, y);
|
|
x = x * (dif / _g);
|
|
x = (x % ((1ll << k) / _g) + ((1ll << k) / _g)) % ((1ll << k) / _g);
|
|
if (dif % _g)
|
|
puts("FOREVER");
|
|
else
|
|
printf("%lld\n", x);
|
|
}
|
|
return 0;
|
|
}
|