(define (extended-euclidean-algorithm a b) (if (= b 0) (list a 1 0) (let* ( (result (extended-euclidean-algorithm b (modulo a b))) (g (car result)) (x (cadr result)) (y (caddr result)) ) (list g y (- x (* y (quotient a b))))))) (define (chinese-remainder-theorem rs ms) (let loop ((r (car rs)) (m (car ms)) (rx (cdr rs)) (mx (cdr ms))) (if (or (null? rx) (null? mx)) (cons r m) (let* ((r0 (car rx)) (m0 (car mx))) (if (and (= r0 -1) (= m0 0)) (cons -1 0) (let* ( (r1 (modulo r0 m0)) (g (gcd m m0)) (l (lcm m m0)) ) (if (not (= (modulo r g) (modulo r1 g))) (cons -1 0) (let* ( (euclid-result (extended-euclidean-algorithm (/ m0 g) (/ m g))) (x (cadr euclid-result)) ) (loop (modulo (+ r1 (* m0 (* (/ (- r r1) g) (modulo x (/ m g))))) l) l (cdr rx) (cdr mx)))))))))) (define yuki187 (let ((r '()) (m '())) (do ((i (string->number (read-line)) (- i 1))) ((zero? i)) (let* ( (vals (map string->number (string-split (read-line) #\space))) (a (car vals)) (b (cadr vals)) ) (set! r (cons a r)) (set! m (cons b m)) ) ) (let* ( (rm (chinese-remainder-theorem r m)) (k (car rm)) (s (cdr rm)) (MOD 1000000007) ) (display (cond ((= k -1) -1) ((zero? k) (modulo s MOD)) (else (modulo k MOD)) ) ) ) ) )