Well, at first: The Big O notation is not related to the programming language, it only depends on the implementation. So it is irrelevant if you do the loops in Java or any other language (besides some optimizations performed by the interpreter/compiler, which will, however, change the program flow)
For the nested loop:
1) sum++
is considered as constant operation with a cost of 1
. Therefore it can be neglected. O(n * 1) = O(n)
2) The outer loop stays roughly the same having O(n-1)
which is equal to O(n)
as constant terms can always be neglected in asymptotic calculations.
3) The inner loop takes log2(n)
steps to finish. In every step n
is reduced to its half, therefore multiplying by 2
takes one step back, which leads to the binary logarithm.
In summary, the complexity is O(n log2(n))
EDIT: funny thing: no one so far has seen that the inner loop has a real complexity of O(infinity)
as the division of some positive number is always greater then 0
... Or am I wrong here?