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

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。