POJ 2115 拓展欧几里德算法

题意

传送门 POJ 2115

题解

求满足如下方程的 xx 最小正值,拓展欧几里德算法即可

Cx+2ky=BACx+2^ky=B-A

要特殊处理 A,B,CA,B,C00 的情况

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

typedef long long ll;
ll A, B, C, k;

ll extgcd(ll a, ll b, ll &x, ll &y)
{
    ll d = a;
    if (b != 0)
    {
        d = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    }
    else
    {
        x = 1, y = 0;
    }
    return d;
}

int main()
{
    while (~scanf("%lld%lld%lld%lld", &A, &B, &C, &k) && (A | B | C | k))
    {
        if (A == B)
        {
            printf("0\n");
            continue;
        }
        if (C == 0)
        {
            printf("FOREVER\n");
            continue;
        }
        ll a = C, b = (ll)1 << k, c = B - A;
        ll x, y;
        ll gcd = extgcd(a, b, x, y);
        if (c % gcd != 0)
        {
            printf("FOREVER\n");
        }
        else
        {
            ll mod = b / gcd;
            x *= c / gcd;
            x = (x % mod + mod) % mod;
            printf("%lld\n", x);
        }
    }
    return 0;
}
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试
应支付0元
点击重新获取
扫码支付

支付成功即可阅读