491人阅读 评论(0)

# Han Xin Count Soldiers

Description

In ancient China, there is a great general named Han Xin. One day he wanted to know how many soldiers he had. So he asked his soldiers to stand in one line for every 3 soldiers, and there are 2 left. Then he asked his soldiers to stand in one line for every 5 soldiers, and there are 3 left. At last he asked them to stand in one line for every 7 soldiers, then there are 2 left. After that he knew he had 1073 soldiers! But now there are a lot of soldiers in front of Han Xin, and he wants to know the number again. He has asked his soldiers stand in lines for n (1 <= n <= 100) rounds. And in the ith round, he asked his soldiers stand in one line for every pi (2 <= pi <= 1000) soldiers, and there is ri (0 <= ri < pi) left. Now can you told Han Xin how many soldiers he have ?

Input

The input has several test cases. For each test case, there is one integer n (1 <= n <= 1000) in the first line. And then there n lines, each line has two integers pi (2 <= pi <= 1000) and ri (0 <= ri < pi). The input is ended by EOF.

Output

For each test case, please output the number of soldiers Han Xin had. If there are more than one solution, please output the smallest positive one. And if there is no solution, please output -1 instead.

Sample Input

3

3 2

5 3

7 2

2

4 1

6 3

Sample Output

23

9

x≡b2(mod a2);    ---   x=b2+a2*y2;

a1*y1 = (b2-b1) (mod a2);

y1 = (b2-b1)*(a1对a2 的逆元)  (mod a2);   //求a1逆元时，a1和a2可以约分，整个方程需要约分。

y1求出后，即可得出一个针对  前两个方程的解，x0;

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
#define ll long long
ll a1,b1,a2,b2;
ll x,y,flag;
ll gcd(ll a,ll b){
return b?gcd(b,a%b):a;
}
ll exgcd(ll a,ll b)
{
ll t,gcd;
if(b==0)
{
x=1,y=0;
return a;
}
gcd=exgcd(b,a%b);
t=x,x=y,y=t-a/b*y;
return gcd;
}
int main()
{
int i,j,k,n;
ll d,t,tem,bb;
while(~scanf("%d",&n)){
flag=0;
scanf("%lld%lld",&a1,&b1);
for(i=1;i<n;i++){
scanf("%lld%lld",&a2,&b2);
d=gcd(a1,a2);
if((b2-b1)%d==0){
exgcd(a1/d,a2/d);//先约分，再求逆元
tem=x;//求出的逆元
k=(tem*(b2-b1)/d)%(a2/d);
b1=(k*a1+b1)%(a1/d*a2);
a1=(a1/d*a2);
}else
flag=1;
}
if(flag==1) printf("-1\n");
else{
b1=(b1+a1)%a1;
if(b1==0) b1=a1;
printf("%lld\n",b1);
}
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：104005次
• 积分：3077
• 等级：
• 排名：第11274名
• 原创：212篇
• 转载：21篇
• 译文：0篇
• 评论：1条
阅读排行
最新评论