# Mirror Reflection Solutions in C++

Number 858

Difficulty Medium

Acceptance 53.7%

Link LeetCode

Other languages —

## Solutions

### C++ solution by haoel/leetcode

// Source : https://leetcode.com/problems/mirror-reflection/description/// Author : Hao Chen// Date : 2018-06-27/** Solution* --------** We know the following things:* 1）every reflection will increase the step of `q`.* 2) when reach the top, the reflection would go down, when reach the bottom the reflection would go up.** So, we can image if there have two walls, left one and right one, then the reflection can go up instanstly,** - the reflection points on left wall would be even times of `q`.* - the reflection points on right wall would be odd times of `q`.** And in the right wall, the receptors `#0` would be the times of `2p`.** So, we need find the least common multiple of `p` and `q`, then we can have the answer.*/class Solution {private://GCD - greatest common divisor 最大公因数int greatestCommonDivisor (int a, int b) {if(b) while((a %= b) && (b %= a));return a + b;}//LCM - least common multiple 最小公倍数int leastCommonMultiple(int a, int b) {return a * b / greatestCommonDivisor(a, b);}public:int mirrorReflection(int p, int q) {int lcm = leastCommonMultiple(p, q);if (lcm % (2*p) == 0 ) return 0;int nq = lcm / q;if (nq % 2 == 0 ) return 2;return 1;}};