# 858. Mirror Reflection

• Time: $O(\log p)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public: int mirrorReflection(int p, int q) { int m = 1; // # of room extension + 1 int n = 1; // # of reflection + 1 while (m * p != n * q) m = ++n * q / p; if (n % 2 == 0) return 2; if (m % 2 == 0) return 0; if (m % 2 == 1) return 1; throw; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution { public int mirrorReflection(int p, int q) { int m = 1; // # of room extension + 1 int n = 1; // # of reflection + 1 while (m * p != n * q) m = ++n * q / p; if (n % 2 == 0) return 2; if (m % 2 == 0) return 0; if (m % 2 == 1) return 1; throw new IllegalArgumentException(); } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution: def mirrorReflection(self, p: int, q: int) -> int: m = 1 # of room extension + 1 n = 1 # of reflection + 1 while m * p != n * q: n += 1 m = n * q // p if m % 2 == 0 and n % 2 == 1: return 0 if m % 2 == 1 and n % 2 == 1: return 1 if m % 2 == 1 and n % 2 == 0: return 2 
Back to top