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.
The laser will hit a receptor when it reaches a corner. The path can be simulated by extending the room horizontally and vertically until the ray hits a receptor. The first meeting point is at the least common multiple (LCM) of p and q. The parity of the number of room extensions determines which receptor is hit.
classSolution {
public:int mirrorReflection(int p, int q) {
int g = gcd(p, q);
int l = p * q / g;
int m = l / q, n = l / p;
if (m %2==0&& n %2==1) return0;
if (m %2==1&& n %2==1) return1;
if (m %2==1&& n %2==0) return2;
return-1;
}
intgcd(int a, int b) { return b ==0? a : gcd(b, a % b); }
};
classSolution {
publicintmirrorReflection(int p, int q) {
int g = gcd(p, q);
int l = p * q / g;
int m = l / q, n = l / p;
if (m % 2 == 0 && n % 2 == 1) return 0;
if (m % 2 == 1 && n % 2 == 1) return 1;
if (m % 2 == 1 && n % 2 == 0) return 2;
return-1;
}
privateintgcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funmirrorReflection(p: Int, q: Int): Int {
fungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
val l = p * q / gcd(p, q)
val m = l / q
val n = l / p
returnwhen {
m % 2==0&& n % 2==1->0 m % 2==1&& n % 2==1->1 m % 2==1&& n % 2==0->2else-> -1 }
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defmirrorReflection(self, p: int, q: int) -> int:
from math import gcd
l = p * q // gcd(p, q)
m, n = l // q, l // p
if m %2==0and n %2==1:
return0if m %2==1and n %2==1:
return1if m %2==1and n %2==0:
return2return-1
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmirror_relection(p: i32, q: i32) -> i32 {
fngcd(a: i32, b: i32) -> i32 { if b ==0 { a } else { gcd(b, a % b) } }
let l = p * q / gcd(p, q);
let m = l / q;
let n = l / p;
if m %2==0&& n %2==1 { return0; }
if m %2==1&& n %2==1 { return1; }
if m %2==1&& n %2==0 { return2; }
-1 }
}