Strange Way to Express Integers(裸的中国剩余定理不互质情况)

本文介绍了一种使用中国剩余定理解决特定数学问题的方法。该问题是确定一个非负整数,仅通过一组由该整数除以不同正整数得到的余数组成的数据。文章提供了一个详细的算法实现示例,并解释了如何从输入数据中找出最小可能的解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Strange Way to Express Integers

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:

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

Hint

All integers in the input and the output are non-negative and can be represented by 64-bit integral types.

裸的中国剩余定理不互质情况的模板套用

不太懂的可以看我的这篇博客

中国剩余定理算法详解(互质与不互质情况)

code:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
bool flag;
ll m[maxn],a[maxn];
ll gcd(ll a,ll b){
    return b ? gcd(b,a%b) : a;
}
ll ex_gcd(ll a,ll b,ll &x,ll &y){
    if(!b){
        x = 1;
        y = 0;
        return a;
    }
    ll g = ex_gcd(b,a%b,y,x);
    y -= a / b * x;
    return g;
}
ll China(int n){
    ll m1 = m[0],a1 = a[0];
    ll m2,a2,k1,k2,x0,g,c;
    ll lcm = m[0];
    for(int i = 1; i < n; i++){
        m2 = m[i];
        a2 = a[i];
        c = a2 - a1;
        g = ex_gcd(m1,m2,k1,k2);
        lcm = lcm * m[i] / gcd(lcm,m[i]);
        if(c % g){
            flag = false;
            return 0;
        }
        x0 = k1 * c / g;
        ll t = m2 / g;
        x0 = (x0 % t + t) % t;
        a1 += m1 * x0;
        m1 = m2 / g * m1;
    }
    return a1;
}
int main(){
    int k;
    while(~scanf("%d",&k)){
        flag = true;
        for(int i = 0; i < k; i++){
            scanf("%lld%lld",&m[i],&a[i]);
        }
        ll ans = China(k);
        if(!flag)
            printf("-1\n");
        else
            printf("%lld\n",ans);

    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值