Welcome to the Divisor Game! This is a classic game theory problem where two players, Alice and Bob, compete in a strategic number game.

Game Rules:

  • ๐ŸŽฎ Alice always goes first
  • ๐Ÿ“ There's a number n written on a chalkboard
  • โœ… On each turn, a player must choose a divisor x where 0 < x < n and n % x == 0
  • ๐Ÿ”„ Replace n with n - x
  • โŒ If a player cannot make a valid move, they lose!

Your Task: Determine if Alice can win this game, assuming both players play optimally (always making the best possible move).

Example: If n = 2, Alice can choose x = 1 (since 2 % 1 == 0), leaving Bob with n = 1. Bob cannot make any valid moves since there's no divisor of 1 that's less than 1, so Alice wins!

Input & Output

example_1.py โ€” Basic Win
$ Input: n = 2
โ€บ Output: true
๐Ÿ’ก Note: Alice chooses x = 1 (since 2 % 1 == 0), leaving Bob with n = 1. Bob cannot make any moves since there's no valid divisor of 1, so Alice wins.
example_2.py โ€” Basic Loss
$ Input: n = 3
โ€บ Output: false
๐Ÿ’ก Note: Alice can only choose x = 1 (since 3 % 1 == 0), leaving Bob with n = 2. Now Bob can choose x = 1, leaving Alice with n = 1. Alice cannot make any moves, so Bob wins.
example_3.py โ€” Edge Case
$ Input: n = 1
โ€บ Output: false
๐Ÿ’ก Note: Alice starts with n = 1 and cannot make any valid moves (no divisor x where 0 < x < 1), so Alice loses immediately.

Visualization

Tap to expand
๐Ÿช The Cookie Jar StrategyGame Rule: Take any number of cookies that divides evenly into the jar totalWinner: Last person to take cookies. Loser: Can't make a valid moveStrategy: Alice (first player) wins if starting with even cookies!๐Ÿช๐Ÿช๐Ÿช๐Ÿช Even CookiesAlice takes 1 cookie(4 รท 1 = 4 โœ“)Bob left with 3 (odd)โœ“ Alice controls the game!๐Ÿช๐Ÿช๐Ÿช Odd CookiesAlice must take 1 cookie(3 รท 1 = 3 โœ“, only option)Bob left with 2 (even)โŒ Bob now controls!๐ŸŽฏ Key InsightAlice wins โŸบ Starting number is even โŸบ n % 2 == 0
Understanding the Visualization
1
Even Cookies = Win
With even cookies, always take 1 cookie, leaving odd for opponent
2
Odd Cookies = Lose
With odd cookies, can only take odd amounts, leaving even for opponent
3
Alice's Strategy
If Alice starts with even cookies, she controls the game and wins
Key Takeaway
๐ŸŽฏ Key Insight: Alice wins if and only if n is even! Even numbers provide winning control, odd numbers force losing positions.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(1)

Single check if number is even or odd

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

No additional space needed

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 1000
  • Both players play optimally
  • Alice always starts first
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~8 min Avg. Time
892 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