# poj2891 Strange Way to Express Integers

Strange Way to Express Integers
 Time Limit: 1000MS Memory Limit: 131072K Total Submissions: 18383 Accepted: 6197

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.

Source

POJ Monthly--2006.07.30, Static

#include<iostream>
#include<cstdio>
#include<iostream>
using namespace std;
long long a[100000],b[100000];
long long exgcd(long long n,long long m,long long &x,long long &y){
if(!m){
x=1;y=0;
return n;
}
long long k=exgcd(m,n%m,x,y);
long long t=x;
x=y;y=t-n/m*y;
return k;
}
int main(){
int n,i,flag;
long long a1,b1,a2,b2,x0,k1=0,k2=0,c,gcd,t;
while(~scanf("%d",&n)){
flag=0;
for(i=1;i<=n;i++){
scanf("%lld%lld",&b[i],&a[i]);
}
a1=a[1];b1=b[1];
for(i=2;i<=n;i++){
a2=a[i];b2=b[i];
c=a2-a1;
gcd=exgcd(b1,b2,k1,k2);
if(c%gcd){
flag=1;
break;
}
x0=c/gcd*k1;
t=b2/gcd;
x0=(x0%t+t)%t;
a1+=b1*x0;
b1=b2/gcd*b1;
}
if(flag==1)printf("-1\n");
else printf("%lld\n",a1);
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120