简体   繁体   中英

How to reduce the time and space complexity of the function foo(n)?

The time complexity for the foo function is O(n^2) but i need to reduce it and cant seem to figure it out.

def bar ( n ):
    if n == 0 :
        return 0
    else :
        return n + bar ( n - 1 )

def foo ( n ):
    if n == 0 :
        return 0
    else :
        return bar ( n ) + foo ( n - 1 )

You can improve bar like this:

def bar(n):
    return n * (n + 1) / 2

This should cut foo to a O(n).

You can even define foo as:

def foo(n):
    return n * (n + 1) / 4 + n * (2 * n + 1) * (n + 1) / 12

To have a function in O(1) :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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