0

My attempt for the Big-O of each of these two algorithms..

1) Algorithm threeD(matrix, n)

// a 3D matrix of size n x n x n

layer ← 0 
while (layer < n)
     row ← 0 
     while (row < layer) 
           col ← 0 
           while (col < row) 
               print matrix[layer][row][col] 
               col ← col + 1 
       done 
       row ← row + 1 
  done 
  layer ← layer * 2 
done

O((n^2)log(n)) because the two outer loops are each O(N) and the innermost one seems to be O(log n)

2) Algorithm Magic(n)

//Integer, n > 0

i ← 0 
while (i < n) 
     j ← 0 
     while (j < power(2,i)) 
          j ← j + 1 
    done 
    i ← i + 1 
done

O(N) for outer loop, O(2^n) for inner? = O(n(2^n))?

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
user3818430
  • 119
  • 1
  • 3
  • 8

1 Answers1

0

1. Algorithm

First of all: This algorithm never terminates due to layer is initiated with zero. layer is only multipyed by 2 so it will never get bigger than zero, specially not bigger than n. To get this work, you have to start with layer > 0.

So lets start with layer = 1.

The time-complexity can be written as T(n) = T(n/2) + n^2.
You can get this by looking that way: At the end the layer is setted at most to n. Then the inner loops do n^2 steps. Bevor that, the layer was only half that big. So you have to do the n^2 steps on the last rould of the outer loop and all stepps of the round bevor wirtten as T(n/2).

The masters theorem gets you Theta(n^2).

2. Algorithm

You can just count the steps:

2^0 + 2^1 + 2^2 + ... + 2^(n-1) = sum_(i=0)^(n-1)2^i = 2^n-1

To get this simplification just take a look at binary numbers: The sum of steps corresponds to a binary number containing only 1's (like 1111 1111). This number equals 2^n-1.

So the time complexity is Theta(2^n)

Notice: Both your Big-O's are not wrong, there are bette boundings.

Community
  • 1
  • 1
AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66