import time

def fac_naive_recursive(n):
    if n <= 1: return 1
    return n * fac_naive_recursive(n-1)  

def fac_tail_recursive(n, a=1):
    if n < 1: return a 
    return fac_tail_recursive(n-1, a*n)   

def fac_for_loop(n, a=1):
    for i in range(1, n+1):
        a = a*i 
    return a

def fac_while_loop(n, a=1):
    while True:
        if n < 1: return a
        a = a*n 
        n = n-1 

def fac_while_loop_2(n, a=1):
    while not n < 1:
        a = a*n 
        n = n-1 
    return a    

# driver code
def timer(f, n):
    print(f'{f.__name__}({n})')
    start = time.time()
    f(n)
    end = time.time()
    print(end - start)
    print()

n = 100
timer(fac_naive_recursive, n)
timer(fac_tail_recursive, n)
timer(fac_for_loop, n)
timer(fac_while_loop, n)
timer(fac_while_loop_2, n)

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: