When Do All Cron Jobs Align?

easy number-theory math simulation 1000 ms · 256 MB

When Do All Cron Jobs Align?

A scheduler starts n periodic jobs at the same instant, second 0 of its clock. After that, job i fires every p_i seconds: at p_i, 2·p_i, 3·p_i, and so on. The on-call team wants to know the first moment after second 0 at which every job fires simultaneously, so they can predict the spike in load.

That moment is the least common multiple of p_1, …, p_n. The scheduler's clock is a 64-bit counter that can represent values up to 10^18; if the first simultaneous firing would happen strictly after that, report that it never happens within range.

Input

The first line contains an integer n (1 ≤ n ≤ 10^5), the number of jobs.

The second line contains n integers p_1, …, p_n (1 ≤ p_i ≤ 10^18), the period of each job in seconds.

Output

Print the smallest t > 0 such that t is a multiple of every p_i. If that value exceeds 10^18, print -1 instead.

Notes

In the first example, jobs fire every 2, 4, and 6 seconds; the first second all three jobs fire together is 12.

In the second example, one job fires every 3 seconds and the other every 10^18 seconds. Since 10^18 is not a multiple of 3, the first joint firing is their product, 3·10^18, which exceeds 10^18 — so the answer is -1.

Example 1

Input

3
2 4 6

Output

12

Example 2

Input

2
3 1000000000000000000

Output

-1

Hints · reveal one at a time if you're stuck

Hint 1

The first joint firing is the least common multiple of all the periods. Think about how to fold the periods in one at a time, using the greatest common divisor, rather than trying to compute a huge product at once.

Hint 2

Divide before you multiply: the gcd of the running value and the next period divides the running value exactly, so the lcm can be built without overflow. The running value never decreases, so as soon as it passes 10^18 the answer is -1 and you can stop.

report an issue Prefer your own editor? sooks prep 60 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.