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!
The big O of a loop is the number of iterations of the loop into number of statements within the 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.
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.
One has to make several assumptions, but the time complexity of this loop appears to be O(√n). The assumptions are:
j
.j
is not modified in the loop bodyn
is not modified in the loop bodyMath.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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With