poj2891 Strange Way to Express Integers

Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m.

“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”

Since Elina is new to programming, this problem is too difficult for her. Can you help her?

Input

The input contains multiple test cases. Each test cases consists of some lines.

Line 1: Contains the integer k.
Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).
Output

Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.

Sample Input

2
8 7
11 9
Sample Output

31

1、n 次 ex_gcd    (mod i并不互质  )

2、M==lcm(m1,m2,m3,m..mn)

3、x要每次取最小整数解

4、就算判-1  也要完成输入

 

参考:https://blog.csdn.net/qq_40872331/article/details/89307732

 

void rep(ll &x,ll k) {
    mod=k;
    x%=mod;
    x+=mod;
    x%=mod;
}
ll phi[maxn];
ll p[maxn];
ll c[maxn];
ll a,b;
ll ex_gcd(ll a,ll b,ll &x,ll &y){
    if(!b){
        x=1;
        y=0;
        return a;
    }
    ll d=ex_gcd(b,a%b,x,y);
    ll z=x;
        x=y;
        y=z-(a/b)*y;
        return d;
}

vector<ll>vec;

char s[maxn];
ll n;


signed main() {
#ifdef local
    freopen("input2.txt","r",stdin);
#endif //local

    while(cin>>n){
    ll a,r;
    ll m=1;
    ll x=1;
    bool yes=1;
    for(ll i=1;i<=n;i++){
            cin>>a>>r;
            if(i==1){
                x=r;
                if(x%a!=r){
                   yes=0;
                   continue;
                }
            m=a;
            }
            else{
                ll tem=gcd(m,a);
                ll tt=r-x;
                if((r-x)%tem){
                    yes=0;
                   continue;
                }
                ll  xx,y;
                ex_gcd(m,a,xx,y);
                rep(xx,a);
                xx*=(r-x)/tem;
                xx%=(a/tem);/// 最小正整数解
                x+=xx*m;
                m=m/tem*a;///(lcm(m1,m2,...mn))
                x%=m;
            }
    }
    if(yes)
    {
    rep(x,m);
    cout<<x<<en;
    }
    else cout<<-1<<en;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值