Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Big O of a For Loop, Iterated Square Root Times?

I am trying to find the Big O for this code fragment:

for (j = 0; j < Math.pow(n,0.5); j++ ) {
 /* some constant operations */
}

Since the loop runs for √n times, I am assuming this for-loop is O(√n). However, I read online that √n = O(logn).

So is this for loop O(√n) or O(logn)?

Thanks!

like image 535
Jay Avatar asked Jan 28 '14 01:01

Jay


People also ask

What is the Big O for a for loop?

The big O of a loop is the number of iterations of the loop into number of statements within the loop.

What is the big O time complexity of a while loop?

Each iteration in the while loop, either one or both indexes move toward each other. In the worst case, only one index moves toward each other at any time. The loop iterates n-1 times, but the time complexity of the entire algorithm is O(n log n) due to sorting.

What is Big O of square root n?

As a result its time complexity is O(sqrt(n)) = O(sqrt(2^s)) = O(2^(s/2)) , where s is the size of the input, which is exponential.


1 Answers

One has to make several assumptions, but the time complexity of this loop appears to be O(√n). The assumptions are:

  • the loop body executes in constant time regardless of the value of j.
  • j is not modified in the loop body
  • n is not modified in the loop body
  • Math.pow(n,0.5) executes in constant time (probably true, but depends on the specific Java execution environment)

As a comment noted, this also assumes that the loop initialization is j = 0 rather than j - 0.

Note that the loop would be much more efficient if it was rewritten:

double limit = Math.pow(n, 0.5);
for (j = 0; j < limit; j++ ) {
 /* some constant operations */
}

(This is a valid refactoring only if the body does not change n.)

like image 172
Ted Hopp Avatar answered Oct 09 '22 19:10

Ted Hopp