HDU 3579

标准同余方程组,只是在求出值后如果为0,应该输出Mi的Lcm;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
LL Ai[50],Ri[50];
LL gcd(LL a, LL b)
{
    return b ? gcd(b,a%b) : a;
}
void Exgcd(LL a,LL b,LL& d,LL& x,LL& y)
{
    if(b == 0) { d = a; x = 1; y = 0;}
    else { Exgcd(b,a%b,d,y,x); y -= x*(a/b); }
}
LL ModN(LL* Ai,LL* Ri,LL n)
{
    LL a1 = Ai[1], r1 = Ri[1];
    LL X,Y,D;
    bool Jug = true;
    for(LL i = 2; i <= n; ++i)
    {
        //if(Jug == false) break;
        LL a = a1, b = Ai[i], c = Ri[i] - r1;
        Exgcd(a,b,D,X,Y);
        if(c % D)
        {
            Jug = false;
            return -1;
        }
        LL t = b / D;
        X = (X * (c / D) % t + t) % t;
        r1 += a1 * X;
        a1 *= Ai[i] / D;
    }
    return r1;
}
int main()
{
    int t;
    LL N;
    int Case = 1;
    cin >> t;
    while(t --)
    {
        cin >> N;
        for(int i = 1; i <= N; ++i)
            cin >> Ai[i];
        for(int i = 1; i <= N; ++i)
            cin >> Ri[i];
        LL ans = ModN(Ai,Ri,N);
        printf("Case %d: ",Case++);
        if(ans == -1) cout << "-1\n";
        else if(ans != 0) cout << ans << endl;
        else {
            LL Lcm = 1;
            for(int i = 1; i <= N; ++i)
                Lcm = Lcm / gcd(Lcm,Ai[i]) * Ai[i];
            cout << Lcm << endl;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值