简体   繁体   English

Python:使用递归有效地确定因素之和

[英]Python: Using recursion to efficiently determine sum of factors

def sof (x, fact):
    if x % fact == 0:
        if fact >= x/fact:
            return fact + x/fact + sof (x,fact - 1)
        else:
            return 1
    else:
        return sof (x,fact-1)

How can I make this program more efficient runtime wise? 如何使该程序在运行时更有效? I am personally exhausted of ideas. 我个人精疲力尽。

I want to be able to run numbers over 4000 without exceeding my recursive limit 我希望能够运行超过4000个数字而又不超过我的递归限制

Here's one way to make the program more efficient , though not necessarily faster . 这是使程序更高效 (尽管不一定更快)的一种方法。 In your code the base case of the recursion: 在您的代码中,递归的基本情况是:

if fact >= x // fact:

is nested inside the remainder check: 嵌套其余检查中:

if x % fact == 0:

Making it possible for your code to keep checking numbers that it doesn't need to. 使您的代码可以不断检查不需要的数字。 (Eg consider a large prime * 2 -- your code keeps checking until fact reaches 1 instead of the halfway point.) (例如,考虑一个大的素数* 2-您的代码会不断检查,直到fact达到1而不是中点为止。)

This isn't a speed issue for the small numbers that this algorithm can handle before the stack overflows. 对于此算法在堆栈溢出之前可以处理的少量数字而言,这不是速度问题。 You only reach 1999 beyond which the stack overflows whereas my rearrangement: 您只达到1999年,在那之后堆栈溢出,而我重新排列:

def sof(number, divisor):
    dividend = number // divisor

    if dividend > divisor:
        return 1

    if number % divisor:
        return sof(number, divisor - 1)

    return divisor + dividend + sof(number, divisor - 1)

can reach 2086 with the same stack size as it avoids those extra recursions. 可以使用相同的堆栈大小达到2086,因为它避免了这些额外的递归。

And that difference increases as you expand the stack via sys.setrecursionlimit() . 当您通过sys.setrecursionlimit()扩展堆栈时,这种差异会增加。

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

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