zoukankan      html  css  js  c++  java
  • 中国剩余定理

    洛谷P1495 https://www.luogu.com.cn/problem/P1495

    ll exgcd(ll a, ll b, ll &x, ll &y)
    {
        if(!b)
        {
            x = 1, y = 0;
            return a;
        }
        int d = exgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    
    ll m[maxn], rest[maxn], n;   //M存储商,rest存储余数
    ll China()
    {
        ll M  = m[1], X = rest[1], x, y;    //假设此时X已经满足前i-1个等式, 即通解为 X + M * k
        for(int i = 2; i <= n; ++i)     //求解一个t1满足: X + t1*M ≡ rest[i] (mod m[i])
        {
            ll d = exgcd(M, m[i], x, y);   //即 t1*M + t2*m[i] = rest[i] - X,首先判断有无解
            if((rest[i] - X) % d) return -1;
            x = (rest[i] - X) / d * x % m[i];   //原先的x 为 t1*M+t2*m[i]=gcd(M, m[i]) = d的解
            X += M * x;   //更新特解X
            M *= m[i] / d;   //更新最小公倍数M
            X %= M;
        }
        return (X + M) % M;   //求得最小正整数解
    }
  • 相关阅读:
    .net core
    asp.net core之abp框架
    C#
    c#
    C#
    C#
    C#
    技术术语
    mysql
    006.内测.情景之迷你财务记账
  • 原文地址:https://www.cnblogs.com/Maxx-el/p/14122546.html
Copyright © 2011-2022 走看看