关于中国剩余定理求最小正整数解的最后取模(初学)
  • 板块学术版
  • 楼主XSean
  • 当前回复5
  • 已保存回复5
  • 发布时间2023/2/10 17:39
  • 上次更新2023/10/24 01:14:35
查看原帖
关于中国剩余定理求最小正整数解的最后取模(初学)
546830
XSean楼主2023/2/10 17:39

最后输出为什么(res % M + M) % M,不应该是模所有mi的最小公倍数吗

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;

const int N = 10;

int n;
int A[N], B[N];

void exgcd(LL a, LL b, LL &x, LL &y)
{
    if (!b) x = 1, y = 0;
    else
    {
        exgcd(b, a % b, y, x);
        y -= a / b * x;
    }
}

int main()
{
    scanf("%d", &n);

    LL M = 1;
    for (int i = 0; i < n; i ++ )
    {
        scanf("%d%d", &A[i], &B[i]);
        M *= A[i];
    }

    LL res = 0;
    for (int i = 0; i < n; i ++ )
    {
        LL Mi = M / A[i];
        LL ti, x;
        exgcd(Mi, A[i], ti, x);
        res += B[i] * Mi * ti;
    }

    cout << (res % M + M) % M << endl;

    return 0;
}
2023/2/10 17:39
加载中...