poj2891

Strange Way to Express Integers

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 a1a2…, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1a2, …, 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 airi (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.

Source


模不互素,不能直接用中国剩余定理,只能每次求2组方程,然后通过他们的lcm求出最后符合左右方程组的解。例如有下面2条同余方程 x ≡ 3 (mod 4),x ≡ 5 (mod 6)。
x = 3 + 4j≡ 5 (mod 6)两边同时减去3
4j ≡ 2 (mod 6)两边同时除于 gcd(4,2,6)
2j ≡ 1 (mod 3)因为2关于3同余1的逆是2
j ≡ 2 (mod 3)
j = 2 + 3k
x = 3 + 4(2 + 3k)这步就是r1 = a1 * x + r1
x = 11 + 12k,m = lcm(m1,m2)
x ≡ 11 (mod 12)
#include <iostream>
using namespace std;
__int64 x, y, t;

__int64 extend_gcd(__int64 a, __int64 b) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    } else {
        __int64 temp = extend_gcd(b, a % b);
        t = x;
        x = y;
        y = t - a / b*y;
        return temp;
    }
}

int main() {
    __int64 a1, a2, r1, r2, c, gcd, temp;
    bool yes;
    int n;
    while (scanf("%d", &n) != -1) {
        yes = false;
        scanf("%I64d %I64d", &a1, &r1);
        for (int i = 0; i < n - 1; i++) {
            scanf("%I64d %I64d", &a2, &r2);
            if (yes)
                continue;
            c = r2 - r1;
            gcd = extend_gcd(a1, a2);
            if (c % gcd != 0) {
                yes = true;
                continue;
            }
            temp = a2 / gcd;
            x = (c / gcd * x % temp + temp) % temp;
            r1 = a1 * x + r1;
            a1 = a1 * a2 / gcd;
        }
        if (yes)
            printf("-1\n");
        else
            printf("%I64d\n", r1);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值