What would be the big o for the algo:
for (i=0; i < n*n; i++)
for(j=0; j<i*i; j++)
As per my understanding
1st loop will loop upto n2 times.
2nd loop will go around n2 times.
Am I right or is it a O(n6) representation?
Also is there a easy way to say when to use log. I have assumed that whenever the loop variable is multiplied the ln function is applied
e.g.: for (i=1; i<n*n i=i*2)
Big o for the loop as per my understanding is O(ln n2) (Am I right again?)
1
These are 2 distinct questions.
1) Yes, this is O(n^6). You can, in fact, directly compute the number of iterations, inner loop makes i^2 iterations, so sum i^2 for i from 0 to n^2
. Input this into Wolfram Alpha or Matlab and you get 1/6 * n^2 * (n^2 + 1) * (2 * n^2 + 1)
2) That is a useful mnemonic. Yes, a log naturally arises when you count the number of times you need to multiply something by itself to get something else. That is not the only place it arises though. Also, O(ln(n^2)) = O(2 * ln(n)) = O(ln(n))
4