Strange Way to Express Integers(中国剩余定理+不互质)

Strange Way to Express Integers

Time Limit:1000MS Memory Limit:131072KB 64bit IO Format:%I64d & %I64u

 

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 ≤ 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

Hint

All integers in the input and the output are non-negative and can be represented by 64-bit integral types.

题意:给你k组数。x%M[i]=A[i];

思路:中国剩余定理,扩展欧几里德

不会的可以参考:http://blog.csdn.net/u010579068/article/details/45422941

转载请注明出处:Strange Way to Express Integers(中国剩余定理+不互质)寻找&星空の孩子

题目链接:http://poj.org/problem?id=2891

#include<stdio.h>
#define LL __int64 void exgcd(LL a,LL b,LL& d,LL& x,LL& y)
{
if(!b){d=a;x=;y=;}
else
{
exgcd(b,a%b,d,y,x);
y-=x*(a/b);
}
}
LL gcd(LL a,LL b)
{
if(!b){return a;}
gcd(b,a%b);
} LL M[],A[]; LL China(int r)
{
LL dm,i,a,b,x,y,d;
LL c,c1,c2;
a=M[];
c1=A[];
for(i=; i<r; i++)
{
b=M[i];
c2=A[i];
exgcd(a,b,d,x,y);
c=c2-c1;
if(c%d) return -;//c一定是d的倍数,如果不是,则,肯定无解
dm=b/d;
x=((x*(c/d))%dm+dm)%dm;//保证x为最小正数//c/dm是余数,系数扩大余数被
c1=a*x+c1;
a=a*dm;
}
if(c1==)//余数为0,说明M[]是等比数列。且余数都为0
{
c1=;
for(i=;i<r;i++)
c1=c1*M[i]/gcd(c1,M[i]);
}
return c1;
}
int main()
{
int n; while(scanf("%d",&n)!=EOF)
{
for(int i=;i<n;i++)
{
scanf("%I64d%I64d",&M[i],&A[i]);
}
if(n==){ printf("%I64d\n",A[]);continue;}
LL ans=China(n);
printf("%I64d\n",ans); }
return ;
}
上一篇:sklearn:Python语言开发的通用机器学习库


下一篇:python运算符重载