[英]What is the recursive algorithm for greatest_divisor() function?
First of all, what I am trying to do is NOT the greatest COMMON divisor .首先,我想做的不是最大的 COMMON divisor 。 I am trying to find the greatest divisor .
我试图找到最大的除数。 For example, for the number 12, my greatest divisor will be 6. For the number 15 it'll be 5 and for 17 it'll be 1.
例如,对于数字 12,我的最大除数将是 6。对于数字 15,它将是 5,对于 17,它将是 1。
What I did was this with an iteration:我所做的是通过迭代:
def greatest_divisor(n):
for d in range(n-1,0,-1):
if n % d == 0:
return d
break
greatest_divisor(12)
>6
which runs properly.运行正常。 What I need is the recursive form of this function.
我需要的是这个 function 的递归形式。 If you could come up with something working I appreciate it!
如果你能想出一些有用的东西,我很感激!
In general you would need fewer iterations if you would find the least divisor (greater than 1) first, and then divide n by that divisor to get the greatest.通常,如果您首先找到最小除数(大于 1),然后将n除以该除数以获得最大除数,则通常需要较少的迭代。 In that case you don't have to iterate more than up to the square root of n .
在这种情况下,您不必迭代超过n的平方根。 When there is none found, then return 1.
如果没有找到,则返回 1。
Here is the iterative solution for that:这是针对该问题的迭代解决方案:
def greatest_divisor(n):
for low in range(2, int(n**0.5)+1):
if n % low == 0:
return n // low
return 1
There is really no gain in making this recursive, as that will be just a case of tail recursion:使这种递归实际上没有任何好处,因为这只是尾递归的一种情况:
def greatest_divisor(n, low=2):
if n % low == 0:
return n // low
if low*low > n:
return 1
return greatest_divisor(n, low+1)
First I would start with a mathematical remark: finding the greatest divisor is the same thing as finding the smallest divisor (but 1), and that smallest divisor will be prime.首先,我将从数学上的评论开始:找到最大的除数与找到最小的除数(但为 1)是一样的,并且那个最小的除数将是素数。 That property could lead to more efficient algorithms if you wanted to search for a great number of values.
如果您想搜索大量值,该属性可能会导致更有效的算法。
Next any iterative method can be rewritten as a recursive one by defining a starting point and a stop condition.接下来,通过定义起点和停止条件,可以将任何迭代方法重写为递归方法。 It is generally avoided because recursive methods have in impact of the stack and break if you recurse too deeply while iterative methods can only require constant resources.
通常会避免这种情况,因为如果递归太深,递归方法会影响堆栈和中断,而迭代方法只需要恒定的资源。
So here a direct transformation of your own code is:所以这里直接转换自己的代码是:
def r_greatest_divisor(n, cur=None):
if cur is None:
cur = n - 1
if cur <= 1:
return 1
if n % cur == 0:
return cur
return r_greatest_divisor(n, cur - 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.