当前位置: 代码迷 >> 综合 >> Problem D:Strange Way to Express Integers(不互素的中国剩余定理)
  详细解决方案

Problem D:Strange Way to Express Integers(不互素的中国剩余定理)

热度:98   发布时间:2024-01-12 16:22:43.0

POJ2891http://poj.org/problem?id=2891

b[i]不保证互素解同余线性方程组,中国剩余定理

 

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-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, 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 Code

#include<iostream>
#include<cstdio>
#define ll long long
using namespace std;
ll exgcd(ll a,ll b,ll &x,ll &y)
{if(!b){x=1;y=0;return a;}ll gcd=exgcd(b,a%b,x,y);ll t=x;x=y;y=t-a/b*y;return gcd;
}
int main()
{ll k;ll n;ll a1,r1;ll x,y;while(scanf("%lld",&n)!=EOF){cin>>a1>>r1;if(n==1){if(a1<=r1){cout<<-1<<endl;}else {cout<<r1<<endl;}continue;}bool flag=true;for(ll i=1;i<n;i++){ll a2,r2;cin>>a2>>r2;if(!flag)continue;if(a2<=r2)flag=false;ll gcd=exgcd(a1,a2,x,y);if((r2-r1)%gcd!=0)flag=false;else{ll temp=a2/gcd;x=((r2-r1)/gcd*x%temp+temp)%temp;r1=x*a1+r1;a1=a1*a2/gcd;r1=(r1%a1+a1)%a1;}}if(flag)cout<<r1<<endl;else cout<<-1<<endl;}return 0;
}
  相关解决方案