Moo Phases
Lately, you have been noticing that all the farm animals around you have been making noises at suspiciously regular intervals. This is definitely not normal, and you think they might be trying to tell you something. You hypothesise that when all the animals make noise at the same time, some significant event will happen. Given the time they will first make noise after a particular time, as well as the periodicity of them making noises thereafter, calculate when they will all sync up, or if it will never happen.
You should also notice that all the animals begin making noises at different times, and might not be in sync. For example, if two animals have a periodicity of two, it does not always mean they are in sync. If one first makes noise at time 1, and the other at time 0, they will never sync up, so you should output as such. That is the significance of the first noise time.
Input
The first line consists of a single integer
, the number of animals you have observed.
The next lines each contain two space-separated integers
and
, the starting time and periodicity thereafter of the
th animal.
Additionally, the lowest common multiple of all is guaranteed to be less than or equal to
.
Output
Output the soonest time in which all animals will make noise at the same time. If they will never sync up, output
.
Example
Input 1
2
1 3
2 4
Output 1
10
In this small example, we can simply list out all the times and see when they first intersect. For animal , we can see that it will be a multiple of
offset by
, so we have
. The second animal will be a multiple of
starting at
, so we have
. It can be seen that they will both make noise at the same time when
.
Input 2
3
0 2
1 4
0 5
Output 2
-1
It can be observed that the first two animals will never sync up. The first one makes noise at all even-numbered times, while the second makes noise at all multiples of offset by
(such as
). It can be seen that these are all odd-numbered, so they will never line up.
Input 3
3
1 2
2 3
3 5
Output 3
23
We will illustrate the sequence of noise-making times for each animal as follows:
- Animal 1:
- Animal 2:
- Animal 3:
The soonest time on which all animals sync up is
Comments