Mirror Reflection - Problem
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.
Given the two integers p and q, return the number of the receptor that the ray meets first.
The test cases are guaranteed so that the ray will meet a receptor eventually.
Input & Output
Example 1 — Basic Case
$
Input:
p = 2, q = 1
›
Output:
2
💡 Note:
The ray starts at (0,0) and first hits the east wall at (2,1). After bouncing, it eventually reaches receptor 2 at the northwest corner (0,2).
Example 2 — Different Path
$
Input:
p = 3, q = 1
›
Output:
1
💡 Note:
The ray bounces multiple times but eventually hits receptor 1 at the northeast corner (3,3).
Example 3 — Direct Hit
$
Input:
p = 1, q = 1
›
Output:
1
💡 Note:
The ray travels diagonally and directly hits receptor 1 at (1,1) without any bounces.
Constraints
- 1 ≤ p ≤ 1000
- 0 < q < p
Visualization
Tap to expand
Understanding the Visualization
1
Square Room Setup
Room with mirrors and 3 receptors at corners
2
Laser Path
Ray bounces off mirrors following reflection laws
3
Hit Receptor
Determine which receptor (0, 1, or 2) is hit first
Key Takeaway
🎯 Key Insight: Use GCD to reduce the problem and parity rules to find the receptor directly
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code