中国剩余定理不互质

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

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

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#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;
}


你可能感兴趣的:(数论)