Python 基礎知識簡單

找出正好有 x 個約數的整數的個數

「尋找恰好具有 x 個除數的整數的數量」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 count_with_x_divisors(n, x),它接受兩個正整數 nx,並傳回 [1, n](含)範圍內恰好具有 x 除數的整數的計數。

數字 k 的除數是整除 k 的任何整數。例如,6 的約數為 1、2、3、6(4 個約數)。

約束條件
  • 1 <= n <= 1000
  • 1 <= x <= 50

範例

Example 1
Input
count_with_x_divisors(10, 2)
Output
4
Explanation

Numbers from 1 to 10 with exactly 2 divisors (i.e., prime numbers): 2, 3, 5, 7. That's 4 numbers.

Example 2
Input
count_with_x_divisors(10, 1)
Output
1
Explanation

Only the number 1 has exactly 1 divisor.

Example 3
Input
count_with_x_divisors(20, 4)
Output
5
Explanation

Numbers from 1-20 with exactly 4 divisors: 6(1,2,3,6), 8(1,2,4,8), 10(1,2,5,10), 14(1,2,7,14), 15(1,3,5,15). That's 5 numbers.

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

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