题目链接:
POJ 2115 C Looooops
题意:
有一个循环语句,变量从A开始,每次都要+C,终止条件是变量==B,每次累加都要mod 2^k.问循环最多执行几次?或者永远循环,
分析:
令K = 2^k.设循环执行了x次则:(A + C * x) mod K = B,也就是A + C * x = B + K * y.
移项可得:C * x - K * y = B - A.那么就是解这个不定方程的最小正整数解x。扩展欧几里德呀~
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
int k;
ll A, B, C, K;
ll ex_gcd(ll a, ll b, ll& x, ll& y)
{
if(b == 0) {
x = 1, y = 0;
return a;
}
ll d = ex_gcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
int main()
{
while(~scanf("%lld%lld%lld%d", &A, &B, &C, &k) && (A || B || C || k)){
if(C == 0){
if(A == B) printf("0\n");
else printf("FOREVER\n");
continue;
}
K = (ll)1 << k;
ll x, y, d;
d = ex_gcd(C, K, x, y);
if((B - A) % d != 0) printf("FOREVER\n");
else {
x = x * (B - A) / d;
ll r = K / d;
x = (x % r + r) % r;
printf("%lld\n", x);
}
}
return 0;
}