C# – Code Forces – Codeforces Round #406B

Its Sunday and it is a good idea to see what CodeForces have done through the week. As in general, lots of good problems. Thus, starting with the easiest one in the second division.

A. The Monster

A monster is chasing after Rick and Morty on another planet. They’re so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, … and Morty screams at times d, d + c, d + 2c, d + 3c, ….

The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.

Input

The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).

The second line contains two integers c and d (1 ≤ c, d ≤ 100).

Output

Print the first time Rick and Morty will scream at the same time, or  - 1 if they will never scream at the same time.

ba58e8e7c79422be337c551c72c11c1b60763948

The trick here is to realize, that the numbers are pretty small and that they cannot repeat per runner. Furthermore, they are only increasing. E.g. Rick cannot shout twice in the same second and the fifth time he screams is always before the sixth time he screams. Thus, if you start writing down the scream times down for our two heroes, the first time you see equal numbers would be automatically the first time they scream together.

Thus, simply add the times they scream into a dictionary as a key (a list is also possible) and check if the list contains a key. If the answer is yes – then the other hero has screamed at this time already and thus this is the answer.

Enjoy the code:

🙂

Tagged with: ,