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

1T1001 \le T \le 100
2N1092 \le N \le 10^9
1SN1 \le S \le N
1K1091 \le K \le 10^9

Output Format

A single integer, the number of moves to reach his faculty, or -1.

Sample Inputs:

Input

Output

Explanation

In first test case, Kyle is on the building that is 4 buildings away from the faculty. He will be reaching his faculty after two moves of 3 buildings.


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)%NP_m =(1+m×K)\%N, where 1 as Kyle's starting point.

Then, his target can be rewrite to this math expression: (1S)%N(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)gcd(K,N) is divisible by (1S)%N(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