Chinese Remainder Theorem
Time limit1sMemory limit256 MB
Given pairs (a_i, b_i), find the largest m such that a_i is congruent to b_i modulo m for every i; since a_i >= b_i, m must divide all differences a_i - b_i.
- Level
Medium6 of 10
- Topics
- Number theory, Math, Greedy, Implementation
- Solved
- No attempts yet
Problem
Johnny is a computer science student. This semester he became well versed with the Chinese Remainder Theorem. While waiting for a next lecture he heard that Maggie complained that she cannot solve her homework; as he heard the familiar words "modulo" and "system of equations" he immediately offered his help to the damsel in distress. It turns out that Maggie's task is much different than those that Johnny is accustomed to solve, it is of the following form:
(where means equivalence modulo) and for the given Maggie should compute the largest such that all of the equations hold. Maggie already started processing the equations and she ensured that for each . Johnny cannot fail and lose his face. Help him to solve the task.
Input
The first line of the input contains a single integer (), denoting the number of equations.
The second line contains integers , each separated by a single space, these are the numbers on the left-hand sides of consecutive equations.
The third and last line contains integers , each separated by a single space, these are the numbers on the right-hand sides of consecutive equations.
The inequality holds for each (). The system of equations is nontrivial: holds for some ().
Output
You should write a single integer in the first and only line of the output: the largest for which the given system of equations is satisfied.
Hint
For Sample 1, the system of equations is satisfied and it is easy to verify that it is not satisfied for .
For Sample 2, the system of equations is satisfied and it is easy to verify that it is not satisfied for .