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 (airi) 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.


题目大意:

给出k组数据,每组数据有2个数,分别是除数和余数,求出满足k组数据的最小整数。


解题思路:

利用扩展欧几里德算法,将每两个同余方程合并为一个同余方程,如此进行下去,直到剩余两个同余方程,求解方程组即可。


代码如下:

#include<iostream>
#include<stdio.h>
using namespace std;
__int64 k,m,t;
//扩展欧几里得求最大公约数和解方程ax+by=gcd(a,b)
__int64 exgcd(__int64 a,__int64 b,__int64 &x,__int64 &y)
{
    if(b==0)
    {
		x=1;
		y=0;
        return a;
    }
    __int64 d=exgcd(b,a%b,x,y);
    t=x;
    x=y;
    y=t-a/b*y;
    return d;
}
int main()
{
    int i,flag;
	__int64 p,q,d,a1,a2,b1,b2,x,c;
    while(scanf("%I64d",&k)!=EOF)
    {
		scanf("%I64d%I64d",&b1,&a1);
		flag=0;//标记方程组是否有解,flag=0有解,否则无解
        for(i=0;i<k-1;i++)
        {
			scanf("%I64d%I64d",&b2,&a2);
			//flag=1时,方程无解,不在执行下面的操作,只是不停的读数据
            if(flag)
				continue;
			d=exgcd(b1,b2,p,q);//b1,b2的最大公约数
			c=a2-a1;
			if(c%d)//如果方程Ax+By=c中的c不能整除b1,b2的最大公约数,则方程无解
			{
				flag=1;
				continue;
			}
			//
			t=b2/d;
			//最小正整数解
			x=(c/d*p%b2+b2)%t;//c/d*p可能为负数,要先模一个b2
			a1=x*b1+a1;
			b1=b1*b2/d;//b1=lcm(b1,b2)
        }
        if(flag)
			printf("-1\n");
		else
			printf("%I64d\n",a1);
	}
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值