码迷,mamicode.com
首页 > 其他好文 > 详细

Strange Way to Express Integers扩展欧几里德

时间:2015-09-27 14:51:48      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
#include <math.h>
#include<string.h>
#include <algorithm>
#define INF 1000000000
using namespace std;
//typedef long long LL;
long long ggcd(long long a,long long b,long long&x,long long&y)
{
    long long d,t;
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }
    d=ggcd(b,a%b,x,y);
    t=x-a/b*y;
    x=y;
    y=t;
     return d;

}
int main()
{
    long long  a1,r1,a2,r2,a,b,c,x0,y0,m,t;
    int i,n;
    while(scanf("%d",&n)!=EOF)
    {
        int bj=1;
        scanf("%lld%lld",&a1,&r1);
        for(i=1;i<n;i++)
        {
            scanf("%lld%lld",&a2,&r2);
            a=a1;
            b=a2;
            c=r2-r1;
            m=ggcd(a,b,x0,y0);
            if(c%m)
                bj=0;
            t=b/m;
            x0*=(c/m);
            x0=(x0%t+t)%t;
            r1=a1*x0+r1;
            a1=a1*(a2/m);


        }
        if(bj==0)
        {
            printf("-1\n");
        }
        else
            printf("%lld\n",r1);
    }
    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 a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ ik) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) 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 ai, ri (1 ≤ ik).

 

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






从后往前推有一个固定的式子;
x=1;y=0;
.
.
.
.

x=y;y=x-a/b*y;


   

Strange Way to Express Integers扩展欧几里德

标签:

原文地址:http://www.cnblogs.com/luckylv/p/4842177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!