版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w144215160044/article/details/51555907
http://poj.org/problem?id=2115
for (variable = A; variable != B; variable += C) statement;题意:在k位的系统内执行这个for循环,问这个循环多少次结束,k为的系统能表示的最大的数为2^k,超出2^k就从0开始
思路:由题意可得出公式(A + C*x) % 2^k = B,由同余模公式得(A%2^k + (C*x%2^k)) % 2^k = B
A + (C*x%2^k)) = B, C*x%2^k) = B-A, C*x ≡ (B-A) (mod) 2^k,即转换成标准的同余方程,根据扩展欧几里得求C的最小逆元就可以了
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <stack>
#include <vector>
#include <map>
using namespace std;
#define N 1002000
#define INF 0xfffffff
#define PI acos (-1.0)
#define EPS 1e-8
#define met(a, b) memset (a, b, sizeof (a))
typedef long long LL;
void Ex_gcd (LL a, LL b, LL &gcd, LL &x, LL &y)
{
if (!b)
{
x = 1;
y = 0;
gcd = a;
}
else
{
Ex_gcd (b, a%b, gcd, y, x);
y -= a/b*x;
}
}
int main ()
{///C*x ≡ (B-A) (mod 2^k)
LL A, B, C, k;
while (scanf ("%I64d %I64d %I64d %I64d", &A, &B, &C, &k), A+B+C+k)
{
LL a = C, b = 1LL<<k;
LL mod = (B-A+b)%b, x, y, gcd;
Ex_gcd (a, b, gcd, x, y);
if (mod%gcd)
{
puts ("FOREVER");
continue;
}
x = x * (mod/gcd) % b;
x = (x%(b/gcd) + b/gcd) % (b/gcd);
printf ("%I64d\n", x);
}
return 0;
}