Strange way to express Integers
Descriptionelina 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 ≤ I ≤ k) 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 ≤ 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
Question:
Given t (a, B) to solve the minimum integer x, so that X satisfies x mod A = B
Solution:
Http://www.cnblogs.com/Enumz/p/4063477.html
Code:
1 /************************************** * *********************************** 2> File Name: poj2891.cpp 3> author: enumz 4> mail: [email protected] 5> created time: tuesday, October 28, 2014, 07 seconds, 6 ******************************* **************************************** */7 8 # include <iostream> 9 # include <cstdio> 10 # include <cstdlib> 11 # include <string> 12 # include <cstring> 13 # include <list> 14 # include <Qu EUE> 15 # include <stack> 16 # include <map> 17 # include <set> 18 # include <algorithm> 19 # include <cmath> 20 # include <bitset> 21 # include <climits> 22 # define maxn 10000023 # define ll long long24 using namespace STD; 25 ll extended_gcd (ll a, LL B, ll & X, ll & Y) // The returned value is gcd (a, B) 26 {27 ll ret, TMP; 28 If (B = 0) 29 {30 x = 1, y = 0; 31 return a; 32} 33 ret = extended_gcd (B, A % B, X, y); 34 TMP = x; 35 x = y; 36 y = TMP-A/B * Y; 37 return ret; 38} 39 Int main () 40 {41 ll n; 42 while (CIN> N) 43 {44 long A1, M1; 45 long A2, m2; 46 CIN> A1> m1; 47 If (n = 1) 48 printf ("% LLD \ n", M1); 49 else50 {51 bool flag = 0; 52 for (INT I = 2; I <= N; I ++) 53 {54 CIN> A2> m2; 55 if (flag = 1) continue; 56 long X, Y; 57 ll ret = extended_gcd (A1, A2, x, y); 58 If (m2-m1) % RET! = 0) 59 flag = 1; 60 else61 {62 long ans1 = (m2-m1)/RET * X; 63 ans1 = ans1 % (A2/RET ); 64 if (ans1 <0) ans1 + = (A2/RET); 65 M1 = ans1 * A1 + M1; 66 a1 = A1 * A2/ret; 67} 68} 69 If (! Flag) 70 cout <M1 <Endl; 71 else72 cout <-1 <Endl; 73} 74} 75 return 0; 76}
Poj2891 -- strange way to express integers (modulus linear equations)