競賽程式設計簡單

使 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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。