Divisor Game Problem
Description
LeetCode Problem 1025.
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:
- Choosing any integer
xwith0 < x < nandn % x == 0. - Replacing the number
non the chalkboard withn - x.
Also, if a player cannot make a move, they lose the game.
Return true if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: n = 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input: n = 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Constraints:
1 <= n <= 1000
Solution
Approach: Parity
Alice wins exactly when n is even. To see why, look at what a move does to the parity of n:
- From an odd
n, every divisorxis odd (an odd number has no even divisors), son - xis always even. - From an even
n, the player can always choosex = 1(whenn >= 2), leavingn - 1, which is odd.
The player stuck at n = 1, which is odd, loses. So the player on an even number can always hand an odd number to the opponent, while the player on an odd number has no choice but to hand back an even one. The numbers keep shrinking, so eventually the player on the odd side reaches 1 and loses. Alice starts on n, so she wins if and only if n is even.
You could also solve it with a DP over 1..n, marking n as winning when some move leads to a losing number; running that for small n is a good way to discover the pattern.
Complexity: O(1) time and space.
class Solution:
def divisorGame(self, n: int) -> bool:
# The player who starts on an even number wins; on an odd number, loses.
return n % 2 == 0