Divisor Game
Alice and Bob take turns playing a game with a starting number n. On each turn, a player chooses any x such that 0 < x < n and n % x == 0, then replaces n with n - x. Alice moves first. If a player cannot make a move, they lose. Return true if Alice can win the game, assuming both players play optimally.
This game can be solved with DP by computing win/lose states from 1 to n. A position i is winning if there exists a valid move x such that i - x is a losing position. The base case: dp[1] = false because no divisor x exists in (0, 1) that divides 1.
The recurrence is:dp[i] = true if there exists x where i % x == 0 and !dp[i - x]. The time complexity is O(n²) but can be optimized to O(1) with the observation that Alice wins if and only if n is even.
Edge cases include n = 1 (Alice loses, no move possible), n = 2 (Alice picks x = 1, n becomes 1, Bob loses), and large n where the DP approach still runs efficiently.
The divisor game DP demonstrates optimal play in a two-player game. A position is winning if there exists a move to a losing position. The inner loop checks all possible divisors x of i, and if moving to i-x forces a loss for the opponent, the current position is winning.
Example Input & Output
Alice picks x=1, n=2; Bob picks x=1, n=1. Bob wins.
Odd number, Alice loses.
Alice picks x=1, n=3 (Bob loses).
Alice picks x=1, n=1. Alice wins.
Alice cannot move. Bob wins.
Algorithm Flow
Solution Approach
Alice and Bob play a game where Alice chooses a divisor x of n (1 < x < n), subtracts it from n, and passes the new n to Bob. The player who cannot make a move (n is odd and has no odd divisor) loses. For even n, Alice can always win by subtracting 1, making n odd. For odd n, any divisor is odd, so subtracting an odd from an odd gives an even number for the opponent. Return true if Alice wins with optimal play.
If n is even, Alice subtracts 1 to make it odd for Bob. Bob then must subtract an odd divisor, making it even again. This cycle continues until n reaches 1, which Bob cannot play because the only divisor is 1 (which is not less than n). Alice wins all even starting numbers.
Time complexity is O(1), space complexity is O(1).
Best Answers
class Solution {
public boolean solution(int n) {
boolean[] dp = new boolean[n + 1];
dp[0] = false;
dp[1] = false;
for (int i = 2; i <= n; i++) {
for (int x = 1; x < i; x++) {
if (i % x == 0 && !dp[i - x]) { dp[i] = true; break; }
}
}
return dp[n];
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
