Solve two congruences

Write codeHard35 min

Your task

Solve a system of two congruences: find the smallest non-negative integer x such that x is congruent to r1 modulo m1 and x is congruent to r2 modulo m2. The moduli are NOT assumed coprime, so a solution exists only when (r2 - r1) is divisible by gcd(m1, m2); in that case the answer is unique modulo lcm(m1, m2). Return that smallest x, or -1 if no solution exists. Use the extended Euclidean algorithm to combine the two congruences.

Examples

crt_two(r1: int, m1: int, r2: int, m2: int) -> int
Example 1
Inputcrt_two(2, 3, 3, 5)
Output8