Python 基礎知識簡單

友善的一對

“友好配對”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 is_friendly_pair(a, b) ,它接受兩個正整數 ab ,如果它們形成友善的對,則傳回 True ,否則傳回 False 。如果兩個數字具有相同的豐度指數,則它們構成友善對。數字 n 的豐度指數定義為 sigma(n) / n,其中 sigma(n)n 的所有除數總和(包括 n 本身)。如果 sigma(a) / a == sigma(b) / b ,則兩個數字是友善的。為了避免浮點問題,請透過交叉相乘進行比較:sigma(a) * b == sigma(b) * a

約束條件
  • 1 <= a, b <= 10^5

範例

Example 1
Input
a = 6, b = 28
Output
True
Explanation

sigma(6) = 1+2+3+6 = 12. sigma(28) = 1+2+4+7+14+28 = 56. Cross check: 12 * 28 = 336, 56 * 6 = 336. They are equal, so they are a friendly pair.

Example 2
Input
a = 30, b = 140
Output
True
Explanation

sigma(30) = 72, sigma(140) = 336. Cross check: 72 * 140 = 10080, 336 * 30 = 10080. Equal, so friendly pair.

Example 3
Input
a = 5, b = 10
Output
False
Explanation

sigma(5) = 6, sigma(10) = 18. Cross check: 6 * 10 = 60, 18 * 5 = 90. Not equal, so not a friendly pair.

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

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