Circular Campus
https://www.hackerrank.com/contests/codenection-2021-open-category-finals/challenges/circular-campus
Question
MMU has a circular campus. We have N buildings arranged in the campus and one of it is Kyle's faculty. Kyle is currently on the building that is S buildings away from his faculty in the clockwise direction (Means his faculty is S buildings away anti clockwise). Now he'll repeat the move: Go to the building that is K buildings away from the building he is currently in, in clockwise direction. How many moves will it take for him to reach his faculty? If he cannot reach his faculty at all, print -1.
Input Format
First line contains an integer T, the number of testcases. The next line is, N S K.
Constraints
Output Format
A single integer, the number of moves to reach his faculty, or -1.
Sample Inputs:
Solution - Optimization Issue
This one can be explained in simple math terms. Since the buildings are in circular, we can convert Kyle's movement as Pm=(1+m×K)%N, where 1 as Kyle's starting point.
Then, his target can be rewrite to this math expression: (1−S)%N.
*Circular means we can modular the number of buildings to make Kyle keep looping in enclosed cycle.
Then, we can check if the gcd(K,N) is divisible by (1−S)%N. If it is not divisible, this implies that no matter how hard Kyle had walked, he is never reaching the destination, we can eliminate early and print -1.
Otherwise, we can simply simulate the path and track the counter.
But, this question is not that simple. As the third case, which introduces large input, this strategy will hit MemoryError, therefore we need to optimize it:
The code above hits memory error, therefore we can optimize it by Extended Euclidean Algorithm to get the m, via modular inverse.
Here's the modification of the code, which passed allt est cases:
Last updated