Two players are playing a game starting with a number n. In each turn, a player can make any one of the subsequent moves:
- Divide n by any of its odd divisors greater than 1. Divisors of a number include the number itself.
- Subtract 1 from n if n > k where k < n.
Player 1 makes the primary move, print "yes" if player 1 wins otherwise print "no" if both play optimally. The player who is unable to make a move loses the game.
Examples:
Input: n = 12, k = 1
Output: Yes
Explanation:
Player 1 first move = 12 / 3 = 4
Player 2 first move = 4 - 1 = 3
Player 1 second move = 3 / 3 = 1
Player 2 second move can be done and hence he loses.
Input: n = 1, k = 1
Output: No
Explanation:
Player 1 first move is not possible because n = k and hence player 1 loses.
Approach: The idea is to analyze the problem for the following 3 cases:
- When integer n is odd, player 1 can divide n by itself, since it is odd and hence n / n = 1, and player 2 loses. Note that here n = 1 is an exception.
- When integer n is even and has no odd divisors greater than 1 then n is of the form 2x. Player 1 is bound to subtract it by 1 making n odd. So if x > 1, player 2 wins. Note that for x = 1, n - 1 is equal to 1, so Player 1 wins.
- When integer n is even and has odd divisors, the task remains to check if n is divisible by 4 then player 1 can divide n by its largest odd factor after which n becomes of the form 2x where x > 1, so again player 1 wins.
- Otherwise, n must be of form 2 * p, where p is odd. If p is prime, player 1 loses since he can either reduce n by 1 or divide it by p both of which would be losing for him. If p is not prime then p must be of the form p1 * p2 where p1 is prime and p2 is any odd number > 1, for which player 1 can win by dividing n by p2.
Below is the implementation of the above approach:
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)