fork download
  1. # http://w...content-available-to-author-only...t.com/2005/11/chinese-remainder-theorem-in-python.html
  2.  
  3. #!/usr/bin/env python
  4.  
  5. def ext_euclid(a, b) :
  6. if b == 0 :
  7. return (a, 1, 0)
  8. else :
  9. (d, xx, yy) = ext_euclid(b, a % b)
  10. x = yy
  11. y = xx - (a / b) * yy
  12. return (d, x, y)
  13.  
  14. def inverse(a, n):
  15. return ext_euclid(a, n)[1]
  16.  
  17. k = int(raw_input())
  18. a = []
  19. n = []
  20. N = []
  21. b = []
  22.  
  23. for i in xrange(0, k):
  24. a_i, n_i = map(long, raw_input().split())
  25. a.append(a_i)
  26. n.append(n_i)
  27.  
  28. n_product = reduce(lambda x, y: x * y, n, 1)
  29.  
  30. for i in xrange(0, k):
  31. N_term = 1
  32. for j in xrange(0, k):
  33. if i != j:
  34. N_term = N_term * n[j]
  35. N.append(N_term)
  36.  
  37. for i in xrange(0, k):
  38. b.append(inverse(N[i], n[i]))
  39.  
  40. x = 0
  41. for i in xrange(0, k):
  42. x = x + a[i] * N[i] * b[i] % n_product
  43.  
  44. print x
Success #stdin #stdout 0.02s 7900KB
stdin
50
24 25
56 57
64 65
67 68
75 76
83 84
86 87
90 91
93 94
93 94
94 95
103 104
108 109
115 116
123 124
127 128
127 128
138 139
140 141
182 183
189 190
205 206
206 207
243 244
243 244
269 270
299 300
401 402
432 433
464 465
473 474
553 554
580 581
622 623
695 696
701 702
779 780
1006 1007
1560 1561
1899 1900
2130 2131
2300 2301
2426 2427
2493 2494
4205 4206
5434 5435
18000 18001
24260 24261
242600 242601
564000 564001
stdout
354176002683770722345561308788158871215722968672217924097811805783761996934391061719090628224661725276684230424019387547648000000000000