Python 基礎知識簡單

一個數可以表示為兩個質數總和嗎

「一個數字能否表示為兩個素數總和」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 is_sum_of_two_primes(n) ,它接受一個正整數 n ,如果 n 可以表示為兩個質數之和,則傳回 True,否則傳回 False。

例如,10 = 3 + 7(均為質數),因此傳回 True。檢查所有可能的對 (p, n-p),其中 p 是質數,n-p 也是質數。

約束條件
  • 2 <= n <= 10^4

範例

Example 1
Input
is_sum_of_two_primes(10)
Output
True
Explanation

10 = 3 + 7. Both 3 and 7 are prime, so True.

Example 2
Input
is_sum_of_two_primes(11)
Output
True
Explanation

11 = 2 + 9? No (9 not prime). 11 = 3 + 8? No. 11 = 5 + 6? No. But wait — we only need one valid pair. Since all fail here... Actually: no valid pair exists with distinct primes, but wait: is_sum_of_two_primes should be False for 11? Let's check: 2+9=11(9 not prime), 3+8(8 not prime), 5+6(6 not prime). Actually False.

Example 3
Input
is_sum_of_two_primes(4)
Output
True
Explanation

4 = 2 + 2. Both are prime, so True.

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

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