Strange Way to Express Integers 扩展欧几里得

来源:互联网 发布:fs2you mac 编辑:程序博客网 时间:2024/06/08 15:35

题意:

给定数组数据a1,r1,a2,r2,使得存在x,x%a1=r1,x%a2=r2,求出最小的x,没有输出-1;

扩展欧几里得的定义自己去网上搜搜,我这讲一些公式的推导。

设 a1*k1+ a2*k2= gcd(a,b); 会求解出特解k1,k2
通解:k1'=k1+a2/gcd*t(t是任意整数);k2'=k2-a1/gcd*t(t是任意整数)
注意一点:当k1%(a2/gcd)时,k1'最小
接下来是a1*k1+ a2*k2= c(r2-r1),(c%gcd==0,有解,否则无解),还是求a1*k1+ a2*k2= gcd(a,b)
然后解出特解k1,k2 ; k1=c/gcd*k1 , k2=c/gcd*k2;即为所求方程的解;通解一样;
通解:k1'=k1+a2/gcd*t(t是任意整数);k2'=k2-a1/gcd*t(t是任意整数)
k1'带入x=a1*k1'+r1得 x=a1*k1+r1+a1*a2/gcd*t(t是任意整数)
注意一点:当x=x1=x1%(a1*a2/gcd)时,x1是最小x,但是这个x1并不满足第三组数据,
但是所求的x一定要满足 x=a1*k1+r1+a1*a2/gcd*t(t是任意整数),即x=x1(mod a1*a2/gcd
相当于a1=a1*a2/gcd,r1=x1;x=r1(mod a1) x=r3(mod a3)(a1,r1已经换了,这样是不是好理解一点)
然后和第三组继续扩展欧几里得,一直到最后一组得出最小x
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;typedef long long ll;ll egcd(ll a,ll b,ll &x,ll &y){    if(b == 0)    {        x = 1 ;y = 0 ;        return a;    }        ll d=egcd(b,a%b,y,x);        y -= (a/b)*x ;    return d;}int main(){    ll k,a1,a2,r1,r2,d,x,y;    while(~scanf("%lld",&k))    {        bool flag=true;        scanf("%lld%lld",&a1,&r1);        k--;        while(k--)        {            scanf("%lld%lld",&a2,&r2);            d=egcd(a1,a2,x,y);            if( (r2-r1)%d )  flag = false ;            if( flag )            {                x = (r2-r1)/d*x ;                y = a2/d ;                x = ( x%y +y)%y ;                r1 = x*a1 + r1 ;                a1 = a1*y ;            }        }        if(flag) printf("%lld\n",r1);        else printf("-1\n");    }    return 0;}

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 mfrom 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
28 711 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.


阅读全文
0 0