chinese_remainder_theorem.sf 443 B

1234567891011121314151617181920212223
  1. #!/usr/bin/ruby
  2. func mul_inv(a, b) {
  3. b == 1 && return 1;
  4. var (b0, x0, x1) = (0, 0, 1);
  5. while (a > 1) {
  6. (a, b, x0, x1) = (b, a % b, x1 - x0*int(a / b), x0);
  7. };
  8. x1 < 0 ? x1+b0 : x1;
  9. }
  10. func chinese_remainder(*n) {
  11. var N = n«*»;
  12. func (*a) {
  13. n.range.map { |i|
  14. var p = int(N / n[i]);
  15. a[i] * mul_inv(p, n[i]) * p;
  16. }.sum
  17. }
  18. }
  19. say chinese_remainder(3, 5, 7)(2, 3, 2);