- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
在我学校的计算机科学 2 类(class)中,我们目前正在探索递归。我们已经使用递归来做诸如阶乘或斐波那契数列之类的事情,但仍然停留在 is_prime(n)
函数上,如果 n 是素数则返回 True,否则返回 False。我们之前迭代地写了一个,但似乎无法弄清楚如何递归地做它。这是我们目前所拥有的:
def is_prime(n):
if n < 2: return False
#1 or 0 is not prime, base case 1
if n == 2 or n == 3: return True
#2 and 3 are both prime, base case 2
if is_prime(n-1): return False
#This checks if n-1 is prime, b/c if so then n must not be prime
#However, this only works b/c the first few numbers have lots of primes
return True
#Only returns True if nothing else has returned
如果有人可以帮助我们一点点,最好是通过一些提示,那就太好了。谢谢!
最佳答案
is_prime(n-1)
对计算 is_prime(n)
不是很有帮助。相反,递归方法将在辅助函数中进行递归,该辅助函数完成大部分计算。
类似 no_divisors(n,k)
如果范围 2, 3, ..., k
不包含则计算结果为 True
n
的除数。很容易看出 no_divisors(n,k)
可以简化为 no_divisors(n,k-1)
。定义此函数,然后根据它定义 is_prime()
。作为一种优化,您可能希望首先检查可被 2 和 3 整除作为基本情况,然后只查看奇数候选除数。
关于python - python 3.x 中的递归 is_prime 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244942/
我正在编写一个程序来查找用户输入n中包含的所有素数。我在使用 is_prime 函数时遇到问题。 #include #include main() { int n; int k; //
我刚刚开始研究 Rust,想制作一些通用的基本数学函数。我有以下 is_prime 函数: fn is_prime(n: i64) -> bool { if n == 2 || n == 3
这是一个来自 codeacademy.com 的问题,我正在那里学习 Python。所以我想要的是定义一个函数来检查一个数是否为素数。如果是,则返回 True。如果不是,则返回 False。 这是我的
我正在尝试用 C 编写一个程序来查找素数并调用一个函数。然而,我不断收到一个奇异的错误,指出被调用对象“is_prime”不是第 22 行中的函数。我设置了一个原型(prototype),但它仍然不起
我很抱歉问了这样一个新手问题,但我在用 Python 编写一个非常基本的程序来检查数字是否为素数时遇到了问题。 这是我的代码: def is_prime(x): if x = 2.')
这个问题已经有答案了: Program that checks if a number is prime number (5 个回答) 已关闭 4 年前。 def is_prime(x): if
我正在尝试编写一个接受整数 x 的函数,如果是素数则返回 True,否则返回 False。它工作正常,除了测试数字 121 时,我不明白为什么。这是我的代码: def is_prime(x):
我有点问题。我正在编写一个 is_prime 函数,但每当我运行它时,它都会在 is_prime(9) 上失败,我不明白为什么: def is_prime(x): if x < 2: ##be
在我学校的计算机科学 2 类(class)中,我们目前正在探索递归。我们已经使用递归来做诸如阶乘或斐波那契数列之类的事情,但仍然停留在 is_prime(n) 函数上,如果 n 是素数则返回 True
我读过 this article其中 /^1?$|^(11+?)\1+$/ Perl 正则表达式用于测试数字是否为质数。 过程: s = '1' * your_number 如果 s 与正则表达式匹配
我是一名优秀的程序员,十分优秀!