Algorithms, Session 1, Complexity and divide and conquer

v1.0.0
2021-10-14

Complexity

Simple exercices

Compute the complexity of the following functions

def sequence(n):
    n = n + 1
    n = n + 2
    n = n * 6
    n = n ** 10
    n = n // 2
    return n

def loop1(n):
    n = n + 1
    i = 0
    while i < n:
        i = i + 1
    n = n * n
    return n

def loop2(n):
    n = n + 1
    i = 1
    while i < n:
        i = 2 * i
    n = n * n
    return n

def b(t):
    n = len(t)
    for j in range(4):
        for i in range(n):
            t[i] *= t[i]

def h(t):
    n = len(t)
    for i in range(n):
        t[i] = 0
        j = n
        while j > 1:
            t[i] += i*j
            j //= 2

Master theorem

def foo(n):
    if n <= 1:
        return
    doOhOne() # doOhOne() runs in O(1) time
    foo(n/2)
    foo(n/2)

def foo2(n):
    if n <= 1:
        return
    doOhN() # doOhN() runs in O(n) time
    foo(n/2)
    foo(n/2)

Divide and conquer