竞争性编程简单

使 GCD 为 k 倍数的最少运算

“使 GCD 为 k 倍数的最小操作”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 min_operations_gcd_k(arr, k),返回使数组中所有元素的最大公约数 (GCD) 成为 k 倍数的最小运算次数。在一次操作中,您可以将数组的任何元素递增或递减 1。

约束条件
  • 1 <= len(arr) <= 10^5
  • 1 <= k <= 10^4
  • 1 <= arr[i] <= 10^9

示例

Example 1
Input
min_operations_gcd_k([4, 5, 6], 5)
Output
2
Explanation

Increment 4 to 5 (1 op) and decrement 6 to 5 (1 op). The array becomes [5, 5, 5] whose GCD is 5, which is a multiple of 5.

Example 2
Input
min_operations_gcd_k([2, 3], 3)
Output
1
Explanation

Increment 2 to 3 (1 op). The array becomes [3, 3] whose GCD is 3, which is a multiple of 3.

Need a Hint?
考虑使用特定于贪婪的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。