Python 基礎知識中等

使用遞歸的質數

「使用遞歸的質數」問題的詳細指南和 Python 實作。

問題陳述

中等

寫一個函數 is_prime(n),使用遞歸檢查給定的正整數 n 是否是質數。如果 n 是質數,則函數應傳回 True,否則傳回 False。質數是大於 1 的數,除了 1 和它本身之外沒有其他約數。

約束條件
  • 1 <= n <= 10000

範例

Example 1
Input
n = 7
Output
True
Explanation

7 is only divisible by 1 and 7, so it is prime.

Example 2
Input
n = 10
Output
False
Explanation

10 is divisible by 2 and 5, so it is not prime.

Example 3
Input
n = 1
Output
False
Explanation

1 is not considered a prime number by definition.

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

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