HDU3579 一元线性同余方程

这题是典型的同余方程组X=Ai(mod Mi)求解问题 需要注意要求输出最小正整数

解 如果同余方程组的解是0 那么应该输出Mi的最小公倍数

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void exgcd(long long a,long long b,long long &d,long long &x,long long &y)
{
    if(b==0)
    {
        x=1,y=0,d=a;
        return;
    }
    exgcd(b,a%b,d,x,y);
    long long temp=x;
    x=y;
    y=temp-(a/b)*y;
}
long long gcd(long long a,long long b)
{
    if(b==0)
        return a;
    return gcd(b,a%b);
}
int main()
{
    long long a[15],b[15],m,n,t,a1,r1,a2,r2,c,d,x,y,gc,a0,b0,s=0;
    cin>>t;
    while(t--)
    {
        bool flag=0;
        gc=1;
        cin>>m;
        for(int i=0; i<m; i++)
            cin>>b[i],gc=gc/gcd(gc,b[i])*b[i];
        for(int i=0; i<m; i++)
            cin>>a[i];
        r1=a[0];
        a1=b[0];
        for(int i=1; i<m; i++)
        {
            a2=b[i],r2=a[i];
            a0=a1,b0=a2,c=r2-r1;
            exgcd(a0,b0,d,x,y);
            if(c%d)
            {
                flag=1;
                break;
            }
            long long t=b0/d;
            x=(x*(c/d)%t+t)%t;
            r1=r1+a1*x;
            a1=a1*(a2/d);
        }
        if(flag)
        {
            cout<<"Case "<<++s<<": "<<-1<<endl;
            continue;
        }
        if(r1==0)
            cout<<"Case "<<++s<<": "<<gc<<endl;
        else
            cout<<"Case "<<++s<<": "<<r1<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值