飞道的博客

剩余定理(孙子定理)

270人阅读  评论(0)

目录

一,剩余定理

二,OJ实战

POJ - 2891 Strange Way to Express Integers


一,剩余定理

 

二,OJ实战

POJ - 2891 Strange Way to Express Integers

题目:

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

Hint

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

代码:


  
  1. #include <iostream>
  2. using namespace std;
  3. #define l long long
  4. l x, y;
  5. l gcd(l a, l b)
  6. {
  7. if (a == 0 || b == 0)
  8. {
  9. x = (b == 0);
  10. y = (a == 0);
  11. return a + b;
  12. }
  13. l r;
  14. if (a < 0)
  15. {
  16. r = gcd(-a, b);
  17. x *= -1;
  18. return r;
  19. }
  20. if (b < 0)
  21. {
  22. r = gcd(a, -b);
  23. y *= -1;
  24. return r;
  25. }
  26. if (a >= b)r = gcd(a%b, b);
  27. else r = gcd(a, b%a);
  28. y -= a / b*x;
  29. x -= b / a*y;
  30. return r;
  31. }
  32. l cheng(l a, l b, l p)
  33. {
  34. if (b == 0) return 0;
  35. if (b < 0) return cheng(a, -b, p)* -1;
  36. l c = cheng(a, b / 2, p);
  37. c = c + c;
  38. if (b % 2)c += a;
  39. return c%p;
  40. }
  41. int main()
  42. {
  43. l t, a1, r1, a2, r2;
  44. while ( cin >> t)
  45. {
  46. a1 = 1, r1 = 0;
  47. while (t--)
  48. {
  49. cin >> a2 >> r2;
  50. if (r1 >= 0)
  51. {
  52. l g = gcd(a1, a2);
  53. if ((r2 - r1) % g)r1 = -1;
  54. else
  55. {
  56. l a3 = a1 / g*a2;
  57. r1 += cheng(cheng((r2 - r1) / g, x, a3), a1, a3);
  58. r1 = (r1%a3 + a3) % a3;
  59. a1 = a3;
  60. }
  61. }
  62. }
  63. cout << r1 << endl;
  64. }
  65. return 0;
  66. }

 


转载:https://blog.csdn.net/nameofcsdn/article/details/115763188
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场