【hdu1573-X问题】拓展欧几里得-同余方程组

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

求小于等于N的正整数中有多少个X满足:

X mod a0 = b0

X mod a1 = b1

……

X mod ai = bi

(0<ai<=10)

输入:第一行为一个正整数T,表示有T组测试数据。每组测试数据的第一行为两个正整数NM (0 < N <= 1000,000,000 , 0 < M <= 10),表示X小于等于N,数组ab中各有M个元素。接下来两行,每行各有M个正整数,分别为ab中的元素。

输出:对应每一组输入,在独立一行中输出一个正整数,表示满足条件的X的个数。

Sample Input

3

10 3

1 2 3

0 1 2

100 7

3 4 5 6 7 8 9

1 2 3 4 5 6 7

10000 10

1 2 3 4 5 6 7 8 9 10

0 1 2 3 4 5 6 7 8 9

Sample Output

1

0

3

题解:同余方程组的裸题。尤其要注意的是所求的是正整数,也就是0的时候要特殊处理。

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

typedef long long LL;
const LL M=20;
LL a[M],b[M];

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

int main()
{
    // freopen("a.in","r",stdin);
    // freopen("a.out","w",stdout);
    LL T;
    scanf("%I64d",&T);
    while(T--)
    {
        LL n,m;
        bool bk=1;
        scanf("%I64d%I64d",&n,&m);
        for(LL i=1;i<=m;i++) scanf("%I64d",&a[i]);
        for(LL i=1;i<=m;i++) scanf("%I64d",&b[i]);
        LL A,B,C,g,x,tx,ty,a1,b1;
        a1=a[1],b1=b[1];
        for(LL i=2;i<=m;i++)
        {
            A=a1;B=a[i];C=b[i]-b1;
            g=exgcd(A,B,tx,ty);
            if(C%g) {bk=0;break;}
            x=((tx*C/g)%(B/g)+(B/g))%(B/g);
            b1=a1*x+b1;
            a1=a1/g*a[i];
        }
        if(bk)
        {
            /*
            得出不定方程a1x+b1=P后,x=0时b1=P。
            因为x可以等于0:ans=(n-b1)/a1+1;
            若P=0,则b1=x=0,不满足正整数,所以减去。
            */
            LL ans=0;
            if(n>=b1) ans=(n-b1)/a1+1;
            if(ans && b1==0) ans--;
            printf("%I64d
",ans);
        }
        else printf("0
");
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/KonjakJuruo/p/5178467.html