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 x with 0 < x < n and n % x == 0
  • Replacing the number n on the chalkboard with n - x

If a player cannot make a move, they lose the game.

Return true if Alice wins the game, assuming both players play optimally.

Input & Output

Example 1 — Alice Loses (Odd)
$ Input: n = 3
Output: false
💡 Note: Alice can only choose x=1, giving Bob n=2. Bob then chooses x=1, giving Alice n=1. Alice cannot move and loses.
Example 2 — Alice Wins (Even)
$ Input: n = 4
Output: true
💡 Note: Alice chooses x=1, giving Bob n=3. Bob must choose x=1, giving Alice n=2. Alice chooses x=1, giving Bob n=1. Bob cannot move and loses.
Example 3 — Base Case
$ Input: n = 2
Output: true
💡 Note: Alice chooses x=1 (only valid divisor), giving Bob n=1. Bob has no valid moves and loses.

Constraints

  • 1 ≤ n ≤ 1000

Visualization

Tap to expand
Divisor Game - Optimal Solution INPUT Chalkboard n = 3 Alice Starts First Bob Second Game Rules: 1. Choose x: 0 < x < n 2. n must be divisible by x 3. Replace n with (n - x) 4. No valid move = LOSE ALGORITHM STEPS 1 Analyze n = 3 Divisors of 3: only 1 2 Alice's Move Must pick x=1, n becomes 2 3 Bob's Move Picks x=1, n becomes 1 4 Alice Stuck! n=1 has no valid x Game Progression: 3 2 Alice Bob x=1 x=1 1 FINAL RESULT Bob Wins! Alice Loses Output: false Optimal Pattern: n=2: Alice wins (x=1) n=3: Bob wins n=4: Alice wins (x=1) n=5: Bob wins Even = Alice, Odd = Bob Key Insight: The winner is determined solely by whether n is even or odd. If n is even, Alice always wins; if n is odd, Bob always wins. This is because subtracting any divisor from an odd number gives an even number (since all divisors of odd numbers are odd). Solution: return n % 2 == 0 TutorialsPoint - Divisor Game | Optimal Solution (Mathematical Pattern)
Asked in
Google 15 Microsoft 12 Facebook 8
66.5K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen