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

    互质情况:

    #include <cstdio>//互质
    int exGcd(int a,int b,int &x,int &y)
    {
        if(b == 0)
        {
            x = 1,y = 0;
            return a;
        }
        int d = exGcd(b,a%b,y,x);
        y -= a/b*x;
        return d;
    }
    int Chinese_Remainder(int mod[],int prime[],int len)
    {
        int i,d,x,y,m,n,ret;
        ret = 0,n = 1;
        for(i=0; i<len; i++) n *= prime[i];
        for(i=0; i<len; i++)
        {
            m = n/prime[i];
            d = exGcd(prime[i],m,x,y);
            ret = (ret+y*m*mod[i])%n;
        }
        return (n+ret%n)%n;
    }
    int main()
    {
        int n,i;
        int mod[15],prime[15];
        while(scanf("%d",&n)&&n)
        {
            for(i=0; i<n; i++)
                scanf("%d%d",&prime[i],&mod[i]);
            printf("%d
    ",Chinese_Remainder(mod,prime,n));
        }
        return 0;
    }
    View Code

    不互质的情况 

    如果flag==0  说明无解

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    typedef long long ll;
    bool flag;
    ll m[100],a[100],lcm;
    ll gcd(ll a,ll b){
        return b ? gcd(b,a%b) : a;
    }
    ll ex_gcd(ll a,ll b,ll &x,ll &y){
        if(!b){
            x = 1;
            y = 0;
            return a;
        }
        ll g = ex_gcd(b,a%b,y,x);
        y -= a / b * x;
        return g;
    }
    ll China(ll n){
        ll m1 = m[0],a1 = a[0];
        ll m2,a2,k1,k2,x0,g,c;
        lcm = m[0];
        for(int i = 1; i < n; i++){
            m2 = m[i];
            a2 = a[i];
            c = a2 - a1;
            g = ex_gcd(m1,m2,k1,k2);
            lcm = lcm * m[i] / gcd(lcm,m[i]);
            if(c % g){
                flag = false;
                return 0;
            }
            x0 = k1 * c / g;
            ll t = m2 / g;
            x0 = (x0 % t + t) % t;
            a1 += m1 * x0;
            m1 = m2 / g * m1;
        }
        return a1;
    }
    int main(){
        int T;
        scanf("%d",&T);
        while(T--){
            ll N;
            int n;
            scanf("%lld%d",&N,&n);
            for(int i = 0; i < n; i++) scanf("%lld",&m[i]);
            for(int i = 0; i < n; i++) scanf("%lld",&a[i]);
            flag = true;
            ll ans = China(n);
            if(!flag || ans > N){
                printf("0
    ");
            }
            else{
                if(ans <= 0) ans += lcm;
                ans = (N - ans) / lcm + 1;
                printf("%lld
    ",ans);
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    awk用法
    cut用法
    优化Linux下的内核TCP参数以提高系统性能
    android开发_LayerlistDrawable(层叠图片)在进度条中的应用
    android开发_文本按钮 与 输入框
    android开发_ViewGroup(组视图)-- 五大布局
    android开发_view和view属性
    android开发_Eclipse新建项目+新建模拟器
    String,StringBuilder,tringBuffer
    zeros()和ones()和eye()
  • 原文地址:https://www.cnblogs.com/bxd123/p/10964533.html
Copyright © 2011-2022 走看看