It is a pretty interesting question I found while doing the online test. There many solutions from different programming languages available from the Internet for us to reference. Personally, I think this is originated from a Mathematics’ question. Some others even talked about algorithms. I can feel the complexity if it involves algorithm. Below is the link to the solutions:
For now, I barely get the concept of how people get it works and personally, I feel the concept may take me a while to understand it. Furthermore, I referred to the Python’s code while picking up the solution.