POJ 1061 同余方程

传送门: POJ 1061

题解

同余方程解法
注意取模时, 不能被整除的模数, 可能结果为负, 所以尽量使扩展欧几里得的a, b为正值

AC code:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;

LL px, py, m, n, L, x, y, f;

LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a;}

void expgcd(LL a, LL b, LL &x, LL &y, LL c) {
    if (!b) {
        if (c % a == 0) {
            x = c / a;
            y = 0;
        }
        else {
            f = 0;
        }
        return;
    }
    expgcd(b, a % b, y, x, c);
    if (!f) return;
    y -= a / b * x;
}

void swap(LL *x, LL *y) {
    LL t = *x;
    *x = *y;
    *y = t;
}

int main() {
    //freopen("in.txt", "r", stdin);
    while (cin >> px >> py >> m >> n >> L) {
        f = 1;
        if (m < n) {
            swap(&m, &n);
            swap(&px, &py);
        }
        expgcd(m - n, L, x, y, py - px);
        //cout << x << endl;
        if (!f) cout << "Impossible" << endl;
        else {
            x %= L;
            if (x < 0) x += L;
            cout << x << endl;
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值