1

I am checking simple order of complexity problems and I found this one:

int example(int max) {
    int i  =  0;
    double x  =  0.0;

    while ( i <= max ) {
        x  =  doStuff(x , i); //doStuff is O(i)
        i  = i + 10 ;
    }
}

We know that doStuff(int x, int i) is of O(i), and that the order of example should be based on max.

Now, i have seen and understood cases of loops running in O(i),O(log i), etc...but how would I get the order of the while loop (and thus the order of example) when the index being checked and also passed to the function does grow in sums different than other usual i++ or 2*i?

Emma
  • 27,428
  • 11
  • 44
  • 69
Lightsong
  • 312
  • 2
  • 8

1 Answers1

1

The case i = i + 10 is not much different from i++:

The order of complexity of the whole algorithm is (where / is integer division, and m is max):

        O(0) + O(10) + O(20) + ... + O((m/10)*10)

As O(x) + O(y) = O(x + y), we can write this as:

        O(10(1+2+3+ ... +m/10))

And we can apply the usual formula for the triangle number:

        O(10(m/10)(m/10 - 1)/2)

We only need the term with the highest order, and can ignore its coefficient:

        = O(m²)

trincot
  • 317,000
  • 35
  • 244
  • 286