We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Let n = number of times each kangaroo hops to eventually land at the same exact distance. To see whether that does happen we need the following expression to be true:
x1 + (v1 * n) = x2 + (v2 * n)
We can check this by looking at the sample input 0, 3, 5, 2 for x1, v1, x2, v2 respectively.
0 + 3n = 5 + 2n
n = 5
This means it takes the kangaroos jumping 5 times to land at the same distance:
0 > 3 > 6 > 9 > 12 > 15
5 > 7 > 9 > 11 > 13 > 15
Now that we know the equation is right, let's move n to one side:
(v1 * n) - (v2 * n) = x2 - x1
n(v1 - v2) = x2 - x1
n = (x2 - x1) / (v1 - v2)
We don't know what the value of n will be, but we know that it must be an integer. If the division solves for a whole integer, we know there is no remainder value. So, we use modular division
(x2 - x1) % (v1 - v2) == 0 (meaning no remainder value, and therefore the division solves for an integer)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Number Line Jumps
You are viewing a single comment's thread. Return to all comments →
Let n = number of times each kangaroo hops to eventually land at the same exact distance. To see whether that does happen we need the following expression to be true:
x1 + (v1 * n) = x2 + (v2 * n)
We can check this by looking at the sample input 0, 3, 5, 2 for x1, v1, x2, v2 respectively.
0 + 3n = 5 + 2n n = 5
This means it takes the kangaroos jumping 5 times to land at the same distance:
0 > 3 > 6 > 9 > 12 > 15
5 > 7 > 9 > 11 > 13 > 15
Now that we know the equation is right, let's move n to one side:
(v1 * n) - (v2 * n) = x2 - x1
n(v1 - v2) = x2 - x1
n = (x2 - x1) / (v1 - v2)
We don't know what the value of n will be, but we know that it must be an integer. If the division solves for a whole integer, we know there is no remainder value. So, we use modular division
(x2 - x1) % (v1 - v2) == 0 (meaning no remainder value, and therefore the division solves for an integer)