Hide

Problem H
Keeping Time

Alice and her pirate gang have successfully followed the instructions of a treasure map they plundered from Chonky Cows. However, the last step says “Continue North for $N$ minutes”. Alice and her pirate gang didn’t bring a clock with them though! They only have two hourglasses, one that measures $A$ minutes and one that measures $B$ minutes. Assuming the time it takes to flip an hourglass over is negligible and that the hourglasses cannot be flipped while only partially done, and that at minute 0, all the hourglasses have all their sand on one side and are ready to be immediately used, help Alice determine the earliest they measure out $N$ consecutive minutes.

Inputs

The first line of input contains three integers, $1 \leq N, A, B \leq 10^{16}$.

Outputs

Output the shortest amount of time it will take to measure out $N$ consecutive minutes using the given hourglasses. If measuring out $N$ consecutive minutes cannot be done, output $-1$.

Explanation of Sample 2

At minute 0, Alice and her pirate gang simultaneously start both hourglasses. At minute 3, the first (3 minute) hourglass has emptied and gets flipped over immediately. At minute 6, the first hourglass has emptied again and gets flipped over immediately. At minute 7 the second (7 minute) hourglass has emptied and get flipped over immediately. Additionally, Alice and her pirate gang start measuring their consecutive block of time at this moment. At minute 9, the first hourglass has emptied again and gets flipped over immediately. At minute 12, the first hourglass has emptied again. At this point Alice and her pirate gang stop measuring their consecutive block of time. They have successfully measured 5 consecutive minutes (from minute 7 to minute 12).

This gives Alice and her pirate a consecutive block of 5 minutes measured out as soon as possible.

Sample Input 1 Sample Output 1
5 12 7
12
Sample Input 2 Sample Output 2
5 3 7
12
Sample Input 3 Sample Output 3
3 2 1
3
Sample Input 4 Sample Output 4
7 2 6
-1

Please log in to submit a solution to this problem

Log in