中国剩余定理不互质

本文介绍了一种解决一元线性同余方程组的方法,该方法不需要模数两两互质,并提供了一个具体的C++实现方案,通过扩展欧几里得算法来寻找解。

解决一元线性同余方程组问题

mod  n1,n2 ,n3......间不要求互质

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <string>
#include <cstring>
#include <ctime>
#define ms(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const int maxn = 100010;

long long exgcd(long long a, long long b, long long &x, long long &y)
{
    if (b == 0)
    {
        x = 1;
        y = 0;
        return a;
    }
    long long ans = exgcd(b, a % b, x, y);
    long long temp = x;
    x = y;
    y = temp - (a / b) * y;
    return ans;
}
int crt(int t)                ///解决一元线性同余方程组问题
{
    int flag = 1;
    long long n1, a1;
    if (t)
    {
        scanf("%lld%lld", &n1, &a1), t--; ///x ≡ a1(mod n1)
    }
    while (t--)
    {
        long long n2, a2, k1, k2;
        scanf("%lld%lld", &n2, &a2);      ///x ≡ a2(mod n2)
        if (flag == 0)
        {
            continue;
        }
        long long d = exgcd(n1, n2, k1, k2);
        if ((a2 - a1) % d != 0)
        {
            flag = 0;
        }
        if (flag)
        {
            k1 = (k1 * (a2 - a1) / d % (n2 / d) + n2 / d) % (n2 / d);
            long long a = n1 * k1 + a1;
            long long n = n1 / d * n2;
            n1 = n;
            a1 = a;
        }
    }
    if (flag)
    {
        return a1;           ///满足所有方程的最小解
    }
    else
    {
        return -1;           ///没有解返回-1
    }
}
int main()
{
    int t;
    while (cin >> t)
    {
        int ans = crt(t);
        cout << ans << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值