class Solution:
def divisorGame(self, n: int) -> bool:
return n % 2 == 0
class Solution {
public:
bool divisorGame(int n) {
return n % 2 == 0;
}
};
class Solution {
public boolean divisorGame(int n) {
return n % 2 == 0;
}
}
var divisorGame = function(n) {
return n % 2 === 0;
};
The Divisor Game is a two-player game involving a single positive integer n. The game is played as follows:
x such that 0 < x < n and n % x == 0 (i.e., x is a positive divisor of n).x, the current player replaces n with n - x.n == 1) loses the game.
The problem asks: Given the starting integer n, determine if the first player (Alice) can guarantee a win, assuming both players play optimally.
At first glance, this problem seems to require simulating all possible moves and outcomes, which could get complicated quickly. A brute-force approach might involve recursively trying every possible divisor and seeing if the first player can force a win. However, with careful observation, we might find patterns or properties that simplify the problem.
By analyzing small values of n, we can look for a winning strategy. For example, for n = 1, no moves are possible, so the first player loses. For n = 2, the first player can subtract 1 (since 1 is a divisor of 2), leaving 1 for the opponent, who then loses. This pattern continues, and by checking more numbers, we might notice that the outcome depends on whether n is even or odd.
This leads us to consider whether parity (even or odd) of n determines the winner, rather than simulating every move.
Let's break down the algorithm step-by-step:
n == 1, Alice cannot move and loses.n == 2, Alice can subtract 1, making n = 1 for Bob, so Alice wins.n and see who wins if both play optimally.n is even and loses when n is odd.n is even, Alice can always subtract 1 (since 1 divides any number), making n odd for Bob.n becomes 1, at which point the player with an odd number loses.n is even. The solution is simply to check the parity of n.This approach avoids recursion or simulation, making it highly efficient.
Let's use n = 4 as an example:
n = 4 (even).
x = 1 (since 1 divides 4), making n = 3 for Bob.
n = 3 (odd). His only move is x = 1, making n = 2 for Alice.
n = 2 (even). She picks x = 1, making n = 1 for Bob.
n = 1 and cannot move. Alice wins.
This pattern holds for any even n: Alice can always force Bob into an odd number, and eventually win.
Brute-force Approach:
O(2^n) or worse.O(1) — Only a single modulo operation is performed.O(1) — No additional data structures are used.This makes the solution extremely efficient, regardless of the input size.
The Divisor Game problem can be elegantly solved by recognizing a simple pattern: the first player (Alice) wins if and only if the starting number n is even. This insight removes the need for complex simulations or recursion. The solution is efficient, requiring only a parity check, and demonstrates the power of pattern recognition and mathematical reasoning in algorithmic problem-solving.