Strange Way to Express Integers(POJ-2891)

本文介绍了一种利用中国剩余定理解决特定数学问题的方法。该问题是寻找满足一系列模运算条件的最小非负整数。文章提供了详细的算法实现,并通过一个示例程序展示了如何使用扩展欧几里得算法来计算解。

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

Problem Description

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

题意:存在一个数 x,满足 x%ai = ri,现给出 n 对 ai 和 ri,求 x 的最小非负整数,如果不存在输出-1

思路:不互素的中国剩余定理模版题。。

Source Program

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define PI acos(-1.0)
#define E 1e-6
#define MOD 16007
#define INF 0x3f3f3f3f
#define N 1000001
#define LL long long
using namespace std;
LL Extended_GCD(LL a,LL b,LL &x,LL &y){
    if(b==0){
        x=1;
        y=0;
        return a;
    }

    LL gcd=Extended_GCD(b,a%b,y,x);
    y=y-a/b*x;
    return gcd;
}
LL gcd(LL a,LL b){
    return b==0?a:gcd(b,a%b);
}
LL CRT(LL W[],LL B[],LL n)
{
    LL res=B[0],Wi=W[0];
    for (LL i=1;i<n;i++)
    {
        LL bi=B[i],wi=W[i];
        LL x,y;
        LL gcd=Extended_GCD(Wi,wi,x,y);
        LL c=bi-res;

        if(c%gcd!=0)
            return -1;

        LL M=wi/gcd;
        res+=Wi*( ((c/gcd*x)%M+M) % M);
        Wi*=M;
    }
    if(res==0)
    {
        res=1;
        for(LL i=0;i<n;i++)
            res=res*W[i]/gcd(res,(LL)W[i]);
    }
    return res;
}
LL a[N],b[N];
int main(){
    LL k;
    while(scanf("%lld",&k)!=EOF&&k){
        for(LL i=0;i<k;i++){
            scanf("%lld%lld",&a[i],&b[i]);//先除数后余数
        }
        printf("%lld\n",CRT(a,b,k));
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值