POJ-2115 C Looooops 扩展GCD

这题就是一个简单扩展GCD,方程为 x*C + y * 2^k = B-A.

代码如下:

#include <cstdlib>

#include <cstdio>

#include <cstring>

#include <iostream>

using namespace std;



typedef long long int Int64;



Int64 A, B, C, K;



Int64 _pow(Int64 a, Int64 b)

{

    Int64 ret = 1;

    while (b) {

        if (b & 1) {

            ret *= a;

        }

        a *= a;

        b >>= 1;

    }

    return ret;

}



Int64 ext_gcd(Int64 a, Int64 b, Int64 &x, Int64 &y)

{

    int temp, ret;

    if (!b) {

        x = 1, y = 0;

        return a;

    }

    ret = ext_gcd(b, a % b, x, y);

    temp = x, x = y, y = temp - a/b*y;

    return ret;

}



int main()

{

    Int64 g, x, y;

    while (scanf("%lld %lld %lld %lld", &A, &B, &C, &K), A|B|C|K) {

        Int64 a = C, b = _pow(2, K);

        g = ext_gcd(a, b, x, y);

        if ((B-A)%g != 0) {

            puts("FOREVER");

            continue;

        }

        x *= ((B-A)/g);

        x %= (b / g);

        if (x < 0) {

            x += b / g;

        }

        cout << x << endl;

    }

    return 0;

}

你可能感兴趣的:(oop)