HDU1573X问题(同余方程组在某个范围内解得个数的问题)

Problem Description
求在小于等于N的正整数中有多少个X满足:X mod a[0] = b[0], X mod a[1] = b[1], X mod a[2] = b[2], …, X mod a[i] = b[i], … (0 < a[i] <= 10)。
 

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

Output
对应每一组输入,在独立一行中输出一个正整数,表示满足条件的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
令数组a的所有数的最小公倍数 为lcm 方程在lcm范围内的非负整数解是a,则有a+lcm*x<=n ,若a!=0 那么x即为所求的解得个数 否则 x-1即为所求
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 15;
typedef long long LL;
LL aa[N],bb[N];
LL gcd(LL a,LL b)
{
    return b==0? a : gcd(b,a%b);
}
void ex_gcd(LL a,LL b,LL &d,LL &x,LL &y)
{
    if(!b){
        x=1;
        y=0;
        d=a;
    }
    else{
    ex_gcd(b,a%b,d,y,x);
    y-=x*(a/b);
    }
}
int main()
{
    int t;
    LL n,m,x,y,d,a,b,c;
    cin>>t;
    while(t--){
        cin>>n>>m;
        LL lcm=1;
        for(int i=1;i<=m;i++){
            cin>>aa[i];
            lcm=lcm/gcd(lcm,aa[i])*aa[i];
        }
        for(int i=1;i<=m;i++)
            cin>>bb[i];
        bool l=1;
        for(int i=2;i<=m;i++){
             c=bb[i]-bb[1];
             a=aa[1],b=aa[i];
            ex_gcd(a,b,d,x,y);
            if(c%d!=0){
                l=0;
                break;
            }
            LL t=b/d;
            x=(x*(c/d)%t+t)%t;
            bb[1]=aa[1]*x+bb[1];
            aa[1]=aa[1]*(aa[i]/d);
        }
        //cout<<"L "<<l<<endl;
        if(!l){
            cout<<"0"<<endl;
            continue;
        }
        LL ans=0;
        if(aa[1]<=n)
            ans=1+(n-bb[1])/lcm;
        if(ans&&bb[1]==0)
            ans--;
        cout<<ans<<endl;
    }
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值