Divisor Game — Solution in Python, Java & C++
Divisor Game solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at Amazon and Adobe.
Divisor Game is an easy coding problem on dynamic programming, math and game theory, asked in Amazon and Adobe interviews.
- Difficulty: Easy
- Topics: Dynamic Programming, Math, Game Theory, Brainteaser
- Asked at: Amazon, Adobe
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Alice and Bob take turns with a number n on a blackboard, Alice moving first. On a turn a player picks any x with 0 < x < n and n % x == 0, then replaces n with n - x. A player who cannot move loses.
Assuming both play optimally, return true if Alice wins.
Example 1
Input: n = 2
Output: true
Explanation: Alice takes x = 1, leaving 1, and Bob has no move.
Example 2
Input: n = 3
Output: false
Explanation: Alice must take x = 1, leaving 2 for Bob, who then wins.
Example 3
Input: n = 4
Output: true
Constraints
1 <= n <= 1000
Hints for Divisor Game
Hint 1
Play out the small cases with a DP over
1 … n: a position wins if some legal move leaves the opponent in a losing position.Hint 2
The pattern that emerges is stark — look at the parity of
n.Hint 3
From an even
n, takingx = 1hands the opponent an odd number; every divisor of an odd number is odd, so they must hand back an even one.
How to solve Divisor Game
From an even n, taking x = 1 hands the opponent an odd number; every divisor of an odd number is odd, so they must hand back an even one. Even positions win, odd positions lose.
Approach
- Return
n % 2 == 0.
Why it works
By induction: 1 is a loss (no move). Odd n has only odd proper divisors, so every move leads to an even number; even n can always subtract 1 to reach an odd number. So odd loses and even wins.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
- The
O(n²)DP over positions reproduces the same parity pattern and is a fine way to discover it.
Reference solution
Python
def divisorGame(n: int) -> bool:
return n % 2 == 0Java
public static boolean divisorGame(int n) {
return n % 2 == 0;
}C++
bool divisorGame(int n) {
return n % 2 == 0;
}JavaScript
var divisorGame = function(n) {
return n % 2 === 0;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 402 dynamic programming problems · the whole catalogue
Learn the technique: Dynamic Programming