Well, first: Big O notation is not related to the programming language, it depends only on the implementation. Therefore, it doesnβt matter if you run loops in Java or in any other language (besides some optimizations performed by the interpreter / compiler, which, however, will change the program flow)
For a nested loop:
1) sum++ considered as a constant operation with a cost of 1 . Therefore, it can be neglected. O(n * 1) = O(n)
2) The outer cycle remains approximately the same as O(n-1) , equal to O(n) , since the constant terms can always be neglected in asymptotic calculations.
3) The inner loop requires steps log2(n) . At each step, n reduces to its half, therefore, multiplication by 2 occurs one step back, which leads to a binary logarithm.
So the complexity is O(n log2(n))
EDIT: the funny thing: so far no one has seen that the inner loop has real O(infinity) complexity, since division of some positive number is always greater than 0 ... Or am I wrong here?
source share