Strange to Express integersTime
limit:1000MS
Memory Limit:131072KB
64bit IO Format:%i64d &%i64u Submit Status Practice POJ 2891Description
Elina is reading a book written by Rujia Liu, which introduces a strange-to express non-negative integers. The 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 R I. If a1, a2, ..., AK is properly chosen, M can is determined, then the pairs (a I, ri) can be used to express m.
"It's easy-to-calculate the pairs from m," said Elina. But what can I find m from the pairs? "
Since Elina is new to programming, this problem was 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≤ i ≤ k ).
Output
Output the non-negative integer m on a separate line for each test case. If There is multiple possible values, output the smallest one. If There is no possible values, output -1.
Sample Input
28 711 9
Sample Output
31
Hint
All integers in the input and the output is non-negative and can is represented by 64-bit integral types.
Test instructions: give you the K group number. X%m[i]=a[i]; thinking: China's residual theorem, expanding Euclid will not be able to refer to: http://blog.csdn.net/u010579068/article/details/45422941 reprint Please specify the Source: Find & Star Child Topic Link: http://poj.org/problem?id=2891
#include <stdio.h>#defineLL __int64voidEXGCD (LL a,ll b,ll& d,ll& x,ll&y) { if(!B) {d=a;x=1; y=0;} Else{EXGCD (b,a%b,d,y,x); Y-=x* (A/b); }}ll gcd (LL a,ll b) {if(!B) {returnA;} GCD (B,a%b);} LL m[55000],a[55000]; LL China (intR) {LL dm,i,a,b,x,y,d; LL c,c1,c2; A=m[0]; C1=a[0]; for(i=1; i<r; i++) {b=M[i]; C2=A[i]; EXGCD (A,b,d,x,y); C=c2-C1; if(c%d)return-1;//c must be a multiple of D, if not, then, definitely no solutiondm=b/D; X= ((x* (C/D))%DM+DM)%DM;//guaranteed x is the minimum positive number//C/DM is the remainder, and the coefficients expand the remainder byc1=a*x+C1; A=a*DM; } if(c1==0)//The remainder is 0, stating m[] is geometric series. And the remainder is 0{C1=1; for(i=0; i<r;i++) C1=c1*m[i]/gcd (C1,m[i]); } returnC1;}intMain () {intN; while(SCANF ("%d", &n)! =EOF) { for(intI=0; i<n;i++) {scanf ("%i64d%i64d",&m[i],&A[i]); } if(n==1) {printf ("%i64d\n", a[0]);Continue;} LL ans=China (n); printf ("%i64d\n", ans); } return 0;}
Strange to Express integers (Chinese remainder theorem + not coprime)