How to optimize traversing a range of numbers?

You should not optimize the traversal, you should eliminate it. Counting one-by-one is slow, so you need to come up with a mathematical formula to produce the count without a loop.

Fortunately, it is not too hard: you start from s, and you add one m times, mod n. Hence, you could compute (s-1) % n and (m-1) % n, add them together, take % n on the final result, and add 1 to convert zero-based result to one-based:

(((s-1) % n) + ((m-1) % n)) % n + 1

Demo.

* Subtract one from s because s is one-based.
** Subtract one from m because the first item is distributed to the initial prisoner.

Leave a Comment