Given an integer N, the task for two players A and B is to make the value of X ( initialized with 1) at least N by multiplying X with any number from the range [2, 9] in alternate turns. Assuming both players play optimally. the task is to find the player to obtain a valuie ≥ N first.
Input: N = 12
Output: Player B
Initially, X = 1.
A multiplies X with 9. Therefore, X = 1 * 9 = 9.
In second turn, B multiplies X with 2. Therefore, X = 9*2 = 18
Therefore, B wins.
Input: N = 10
Output: Player B
Approach: The idea is to use the concept of combinatorial game theory. Find the positions from where, if a number is multiplied with X leads to victory and also the positions which lead to a loss. Below are the steps:
- In combinatorial game theory, let’s define that an N position is a position from which the next player to move wins if he plays optimally and P-position is a position where the next player to move always loses if his opponent plays optimally.
- The lowest position that can be reached up to N is, say res = ceil(N/9). Therefore, all the positions from [res, res + 1, res + 2, ….., N – 1] are N positions.
- The only positions that are forced to move to [res, res + 1, …, (N – 1)] are those that when multiplied by 2, and they lie in that interval, which is given by Y = ceil(res/2),
- Therefore, [Y, Y + 1, …, (res – 1)] are all the P-positions.
- After repeating the above steps until the interval containing 1 is found if 1 is an N-position then A wins, else B wins.
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.