【hdu3579-Hello Kiki】拓展欧几里得-同余方程组

【hdu3579-Hello Kiki】拓展欧几里得-同余方程组

 

http://acm.hdu.edu.cn/showproblem.php?pid=3579

题解:同余方程组的裸题。注意输出是最小的正整数,不包括0。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;

typedef long long LL;
const int N=20;

LL exgcd(LL a,LL b,LL &x,LL &y)
{
    if(b==0) {x=1,y=0; return a;}
    LL tx,ty;
    LL d=exgcd(b,a%b,tx,ty);
    x=ty;
    y=tx-(a/b)*ty;
    return d;
}

int main()
{
    // freopen("a.in","r",stdin);
    // freopen("a.out","w",stdout);
    int n,T;
    scanf("%d",&T);
    LL a[N],b[N];
    for(int TT=1;TT<=T;TT++)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++) scanf("%I64d",&a[i]);
        for(int i=1;i<=n;i++) scanf("%I64d",&b[i]);
        LL a1=a[1],b1=b[1];
        bool bk=1;
        for(int i=2;i<=n;i++)
        {
            LL A=a1,B=a[i],C=b[i]-b1,x,y;
            LL g=exgcd(A,B,x,y);
            if(C%g) {bk=0;break;}
            x=((x*C/g)%(B/g)+(B/g))%(B/g);
            b1=a1*x+b1;
            a1=a1/g*a[i];
        }
        if(!bk) printf("Case %d: -1\n",TT);
        else{
            /*
            a1x+b1=P;(a1>=0,P求的是最小正整数)
            b1!=0 --> x=0,b1=P
            b1==0 --> x=1,a1=P
            */
            if(b1) printf("Case %d: %I64d\n",TT,b1);
            else printf("Case %d: %I64d\n",TT,a1);
        }
    }
    return 0;
}
View Code

 

posted @ 2016-02-02 20:42 拦路雨偏似雪花 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值