Skip to main content
LIVE CONTEST: ALGOR Contest: Round #4 (Special Challenge) is live now!

~/algor $ cat problems/sonlar-qoldiqlar-sistemasi

System of remainders

Medium 1000 ms 128 MB 56%
Share

You are given positive integers $m_{1}$, $m_{2}$ and integers $r_{1}$, $r_{2}$. Find the smallest non-negative integer $x$ that leaves remainder $r_{1}$ when divided by $m_{1}$ and remainder $r_{2}$ when divided by $m_{2}$. If there is no such number, print $-1$. $m_{1}$ and $m_{2}$ are not necessarily coprime.

Two rows of numbers with different steps: the first common value is highlighted

Input

The first line contains two integers: $m_{1}$ and $r_{1}$. The second line contains two integers: $m_{2}$ and $r_{2}$.

Output

One integer — $x$ or $-1$.

Note

$1 \le m_{1}, m_{2} \le 10^{9}$
$0 \le r_{1} \lt m_{1}$, $0 \le r_{2} \lt m_{2}$

Examples

Input #1
3 2
5 3
Output #1
8
Input #2
4 1
6 2
Output #2
-1

Sign in to submit a solution

Signing up is free and takes a minute.