Mirror Reflection
This problem can be approached by understanding how the ray moves in the room. We can extend the room virtually by mirroring it multiple times. This way, we can see that the ray moves in a straight line.
We need to determine when the ray reaches one of the receptors for the first time. This happens when the ray reaches a corner of the room.
Here’s the code:


The code first computes the greatest common divisor of p
and q
and divides both by that value. Then, depending on the parity of p
and q
, the function returns the receptor number that the ray meets first.
The time complexity is O(log min(p, q)) due to the gcd computation, and the space complexity is O(1), as only a constant amount of extra space is used.