Mirror Reflection

medium math geometry number theory

Problem

A square room has mirrors on all four walls. Three receptors are at corners 0, 1, and 2 (every corner except the southwest). The room has side length p and a laser fires from the southwest corner, first striking the east wall at distance q from receptor 0. Return which receptor the ray hits first.

Inputp = 2, q = 1
Output2
The ray meets receptor 2 after one bounce.

from math import gcd

def mirror_reflection(p, q):
    g = gcd(p, q)
    p, q = (p // g) % 2, (q // g) % 2
    if p and q:
        return 1
    return 0 if p else 2
function mirrorReflection(p, q) {
  const gcd = (a, b) => b ? gcd(b, a % b) : a;
  const g = gcd(p, q);
  p = (p / g) % 2;
  q = (q / g) % 2;
  if (p && q) return 1;
  return p ? 0 : 2;
}
class Solution {
    public int mirrorReflection(int p, int q) {
        int g = gcd(p, q);
        p = (p / g) % 2;
        q = (q / g) % 2;
        if (p == 1 && q == 1) return 1;
        return p == 1 ? 0 : 2;
    }
    private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}
int mirrorReflection(int p, int q) {
    int g = __gcd(p, q);
    p = (p / g) % 2;
    q = (q / g) % 2;
    if (p && q) return 1;
    return p ? 0 : 2;
}
Time: O(log(min(p,q))) Space: O(1)