简体   繁体   English

递归函数查找同时被三个数字整除的最小数字

[英]Recursive function to find the smallest number divisible by three numbers simultaneously

I am trying to find the smallest integer that is divisible by 2, 3, and 5 through a recursive function as follows: 我试图通过递归函数找到可被2、3和5整除的最小整数,如下所示:

def recursiva(n):

    lista = []
    if(n%2==0 and n%3==0 and n%10==0):
        lista.append(n)

    n = n - 1
    recursiva(n)

    return min(lista)

recursiva(100)

But even for small numbers like 100 I am having stack overflow, as seen in the error message: 但是即使对于像100这样的小数字,我也会出现堆栈溢出,如错误消息所示:

RecursionError: maximum recursion depth exceeded in comparison

I wonder: 我想知道:

  • What am I doing wrong? 我究竟做错了什么?
  • Is there any way, instead of passing a fixed value per parameter, to make the function look for the smallest number divisible by 2,3 and 5 within the set of integers? 有什么方法可以使函数寻找整数集中2、3和5可除的最小数字,而不是为每个参数传递固定值?

To fix it, before calling recursiva() again, check if n is equal or less than 0 ( n<=0 ). 要解决此问题,请再次调用recursiva() ,然后检查n是否等于或小于0( n<=0 )。 Without a condition, it will not stop, and will loop infinitely. 没有条件,它将不会停止,并且会无限循环。

In a recursive function you need to have at least 2 possible return statements, 1 where some end condition is met and the answer is returned and 1 where what is returned is new call to the function with some modified input. 在递归函数中,您至少需要2条可能的return语句,其中1条满足某些结束条件并返回答案,而1条返回的是对函数进行了一些修改后的新调用。

Additionally for your problem you need a method of saving the results of the previous calls somewhere. 另外,对于您的问题,您需要一种将先前调用的结果保存在某处的方法。 You might consider passing the list of successful calls as a parameter to the function. 您可以考虑将成功调用列表作为参数传递给函数。

I got it like this: 我是这样的:

def recursiva(n = 1):
    if (n%2==0 and n%3==0 and n%10==0):
        return n
    else:
        return recursiva(n+1)
recursiva()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM