LeetCode //C - 1025. Divisor Game

1025. Divisor Game

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.

Also, if a player cannot make a move, they lose the game.

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

Example 1:

Input: n = 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.

Example 2:

Input: n = 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.

Constraints:
  • 1 <= n <= 1000

From: LeetCode

Link: 1025. Divisor Game


Solution:

Ideas:

The result only depends on whether n is even or odd.

  • If n is even, Alice can always choose an odd divisor x, so n - x becomes odd for Bob.
  • If n is odd, every divisor x of n is also odd, so n - x becomes even for Bob.

So:

  • starting with an even number is a winning position
  • starting with an odd number is a losing position

Therefore, Alice wins iff n is even.

Code:
c 复制代码
bool divisorGame(int n) {
    return (n % 2 == 0);
}
相关推荐
从零开始的代码生活_33 分钟前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI1 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅
atunet1 小时前
关于图算法中的连通分量检测与最小割问题7
算法
心运软件2 小时前
银行客户流失预测(Python 完整实战)
算法
邪神与厨二病2 小时前
牛客周赛 Round 153
python·算法
qizayaoshuap4 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语4 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet4 小时前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_5 小时前
rog_map参数理解
算法
春日见5 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表