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);
}
相关推荐
玖玥拾1 天前
C/C++ 基础笔记(八)
c语言·c++
团象科技1 天前
走访近百支出海技术团队后的海外云计算资源选型实操观察
大数据·人工智能·算法
勤自省1 天前
吴恩达机器学习课程实验:线性回归模型入门(课后实验)
人工智能·算法·机器学习·回归·线性回归
ChillCoding1 天前
更新中:C++ STL库,查找排序(基础算法),数据结构,数学算法,竞赛相关基础
数据结构·c++·算法
智者知已应修善业1 天前
【51单片机使用IO组赋值方法实现无源蜂鸣器响时LED12亮不响时34亮】2024-3-7
c++·经验分享·笔记·算法·51单片机
珊瑚里的鱼1 天前
【动态规划】按摩师
算法·动态规划
Fms_Sa1 天前
贪心算法-背包问题
算法·贪心算法·c#
大雨淅淅1 天前
【机器人】ROS2 机械臂控制(MoveIt2)从入门到实战
人工智能·python·神经网络·学习·算法·机器学习·机器人
智者知已应修善业1 天前
【51单片机0.1秒计时到21.0时点亮LED】2024-1-5
c++·经验分享·笔记·算法·51单片机
apcipot_rain1 天前
计科八股20260606——二叉树、PCA、图深度学习、进程上下文、C语言预编译、文件读写、单精度浮点数
c语言·数据结构·算法·pca·图神经网络