Strange Way to Express Integers


Time Limit: 1000MS

 

Memory Limit: 131072K

Total Submissions: 12338

 

Accepted: 3903


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-negativem, divide it by every ai (1 ≤ik) to find the remainder ri. Ifa1, a2, …,ak are properly chosen, m can be determined, then the pairs (ai,ri) can be used to expressm.

“It is easy to calculate the pairs from m, ” said Elina. “But how can I findm 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 ≤ ik).


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.

//题意:

给定一个数n,接下来输入n对数,每对数是一个m,一个r,表示x%m=r。让求x的值。

思路:

这个题也是一个裸的中国剩余定理的题,只不过这个题给的p[i],p[j]不互素,所以得两两求解,在求解的同时加上取余即可防止超出long  long的范围(不然会RE)

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
ll extgcd(ll a,ll b,ll &x,ll &y)
{
	ll t,tmp;
	if(!b)
	{
		x=1;
		y=0;
		return a;
	}
	else
	{
		t=extgcd(b,a%b,x,y);
		tmp=x;
		x=y;
		y=tmp-(a/b*y);
		return t;
	}
}
ll x,y;
int main()
{
	ll a1,a2,b1,b2,k,c,n,m,i,j;
	while(scanf("%lld",&k)!=EOF)
	{
		scanf("%lld%lld",&a1,&b1);
		bool flag=false;
		for(i=1;i<k;i++)
		{
			scanf("%lld%lld",&a2,&b2);
			if(flag)
				continue;
			ll e=extgcd(a1,a2,x,y);//求得a1,a2的最大公约数
			c=b2-b1;
			if(c%e)
			{
				flag=true;
				continue;
			}
			ll M=a2/e;
			x=(x*c/e%M+M)%M;//求得最小的解 
			b1=a1*x+b1;
			a1=a1*a2/e;//a1重新赋值为a1,a2的最小公倍数
		}
		if(flag)
			printf("-1\n");
		else
			printf("%lld\n",b1);
	}
	return 0;
}

 


#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<algorithm>
#define INF 0x3f3f3f3f
#define IN __int64
#define ull unsigned long long
#define ll long long
#define N 10000010
using namespace std;
int n;
ll p[N],b[N];
ll extgcd(ll a,ll b,ll &x,ll &y)
{
	if(!b)
	{
		x=1;
		y=0;
	}
	else
	{
		extgcd(b,a%b,y,x);
		y-=x*(a/b);
	}
}
ll chinese_remainder()
{
	ll M=1;
	for(int i=0;i<n;i++)
		M*=p[i];
	ll m;
	ll x,y;
	ll ans=0;
	for(int i=0;i<n;i++)
	{
		m=M/p[i];
		extgcd(m,p[i],x,y);
		ans=(ans+x*m*b[i])%M;
	}
	return (ans+M)%M;
}
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		for(int i=0;i<n;i++)
			scanf("%lld%lld",&p[i],&b[i]);
		printf("%lld\n",chinese_remainder());
	}
	return 0;
}