Reputation: 21
It is a problem from an algorithm textbook, i think the time complexity is log(n!), but my classmate says it is nlog(n). Thanks very much for you reply!!
count ← 0
for i ← 1 to n do
j ← ⌊n/2⌋
while j ≥ 1 do
count ← count + 1
if j is odd then
j←0
else
j ← j/2
end if
end while
end for
Upvotes: 1
Views: 172
Reputation: 183978
I think the time complexity is
log(n!)
, but my classmate says it isnlog(n)
.
You're both right. As can be seen from Stirling's formula,
log n! = n * log n - n +O(log(n)),
(log
is the natural logarithm here) more precisely:
log n! = (n + 1/2) * log n - n + 1/2 * log (2π) + O(1/n)
so O(log n!)
and O(n*log n)
are the same class.
Upvotes: 3
Reputation: 28850
Taking the worst case, n = 2p
So, n * log
2(n)
iterations, or time complexity of O(n log(n))
--
(As per comment, the log base is not necessary in complexity, as log2(x) is actually log(x)/log(2) i.e. log(x) multiplied by constant)
Upvotes: 1