Determining and bounding number of steps for a algorithm

56 Views Asked by At
def function(n):
    i = 1
    while i <= n*n:
        a = n*n

        while a > n:
            a=a-1

        i = i + 1

Determine a summation representing the number of steps this algorithm takes.

My attempt:

$ f(n) = \sum\limits_{i=1}^{n^2} \sum\limits_{a = 1}^{n^2 -n} 1 = \sum\limits_{i=1}^{n^2} (n^2 -n) = n^2 (n^2 - n) = n^4 - n^3$.

So we have $ \ \Theta(n^4)$

1

There are 1 best solutions below

3
On

$i$ goes from $1\rightarrow n^2$ and $a$ from $n^2 \rightarrow n+1$. Total steps are $$\sum_{i=1}^{n^2}\sum_{a=n+1}^{n^2}1=\sum_{i=1}^{n^2}n^2-n=n^2(n^2-n)$$ so yes you are correct.