Strange Way to Express Integers (poj 2891)

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

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

num%a1=r1

num%a2=r2

......

num%an=rn

像中国剩余定理,但是r1,r2......rn并不互质。那就直接解同余方程组。

先解方程一:可得num=c+mt;

代入方程二:可得c+mt+y*a2=r2,移项:mt+y*a2=r2,解t=c1+m1t,num2=c+m*(c1+m1t);

类推,解出最后一个num;

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#define INF 1005

using namespace std;

long long k;
long long a[INF],r[INF];//分别表示an与rn 

long long extgcd(long long a,long long b,long long& x,long long& y)
{
    long long d=a;
    if(b!=0){
        d=extgcd(b,a%b,y,x);
        y-=(a/b)*x;
    }
    else{
        x=1,y=0;
    }
    return d;
}
long long linear_congruence(int n)
{
    long long c=0,m=1;
    for(int i=0;i<n;i++){
        long long ai=m,bi=r[i]-c;
        long long x,y;
        long long g=extgcd(ai,a[i],x,y);
        if(bi%g!=0) return -1;
        long long m1=a[i]/g;
        c=((x*bi/g)%m1+m1)%m1*m+c;
        m=m1*m;
    }
    return c;
}

int main()
{
    while(scanf("%lld",&k)!=EOF){
        for(int i=0;i<k;i++){
            scanf("%d%d",&a[i],&r[i]);
        }
        long long num=linear_congruence(k);
        cout<<num<<endl;
    }
}
/*将方程一般化为aix%biy=ri;
数组设a[n],b[n],r[n];*/


long long linear_congruence(int n)
{
    long long c=0,m=1;
    for(int i=0;i<n;i++){
        long long ai=m*a[i],ri=r[i]-c*a[i];
        long long x,y;
        long long g=extgcd(ai,b[i],x,y);
        if(ri%g!=0) return -1;
        long long m1=b[i]/g;
        c=((x*ri/g)%m1+m1)%m1*m+c;
        m=m1*m;
    }
    return c;
}

阅读更多
个人分类: 同余方程组
上一篇Biorhythms (poj 1006)
下一篇Nim (poj 2975)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭