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


目录
相关文章
|
3月前
|
C++
【PTA】L1-046 整除光棍(C++)
【PTA】L1-046 整除光棍(C++)
24 1
|
3月前
【LeetCode刷题】两数之和、两数相加
【LeetCode刷题】两数之和、两数相加
|
4月前
|
存储 算法 测试技术
|
4月前
|
C++
【PTA】​ L1-080 乘法口诀数列​(C++)
【PTA】​ L1-080 乘法口诀数列​(C++)
80 0
【PTA】​ L1-080 乘法口诀数列​(C++)
|
4月前
|
C++
【PTA】L1-025 正整数A+B (C++)
【PTA】L1-025 正整数A+B (C++)
92 0
【PTA】L1-025 正整数A+B (C++)
|
12月前
|
存储
每日一题(两数相加)
每日一题(两数相加)
|
Java Python
leetcode每日一题.445:两数相加II
leetcode每日一题.445:两数相加II
77 0
每日一题——最大回文数乘积
每日一题——最大回文数乘积
98 0
LeetCode每日一题(1)——最大回文数乘积
LeetCode每日一题(1)最大回文数乘积 1.题目 2.示例 3.思路 1.生成位数符合要求的递减的回文数 2.判断回文数是否符合要求 4.代码 5.复杂度分析
|
存储 算法 Go
【刷题】两数相加
【刷题】两数相加
【刷题】两数相加