2

Given the following algorithm :

    input : a (integer), b (integer != 0)

    result = 0;
    while(a >= b) 
    {
       a = a - b;
       result = result + 1;
    }

    return result;

How to find the number of instructions and the time complexity of this kind of algorithm since we don't know neither a nor b nor the number of iteration in advance ?

Spn
  • 143
  • 4

2 Answers2

1

Your algorithm makes exactly $\lfloor\frac{a}{b}\rfloor$ iterations of while loop.

If we suppose that the size of the inputs is $n=max\{a,b\}$ then your algorithm will make at most $n$ iterations; when $a=n$ and $b=1$.

Therefore, with this notation, your algorithm (on a high level) runs in $O(n)$ time complexity.


If you want to analyze it deeper, including the complexity of addition and subtraction which are $\Theta(n)$ for $n$-digit numbers, things get more complicated because $n$ we defined above was not the number of digits (decimal representation) but a value (unary representation).
As it can be shown, the base in which we represent numbers is not relevant, so the overall analyzed algorithm, having in mind also the properties of big-O and big-Theta runs in $O(n^2)$ where $n$ is the number of digits (in any base).

Sandro Lovnički
  • 1,221
  • 1
  • 7
  • 17
0

As your while is run in $\frac{a}{b}$-times, and inside your loop there just an add and subtraction, the time complexity is $\Theta(\frac{a}{b})$.

OmG
  • 3,612
  • 1
  • 15
  • 23