Predict the output
What does this print?
import math
for n in (10, 1000):
need = math.log2(math.factorial(n))
print(n, round(need), round(n * math.log2(n)))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 10 22 33 1000 8529 9966
Right: log₂(n!) tracks n log₂ n, a little below it.
The lower bound and n log₂ n stay within a constant factor of each other, which is why O(n log n) is optimal for comparison sorts.
Why not the others?
- B 10 10 33 1000 1000 9966. log₂(n!) grows faster than n.
- C 10 33 33 1000 9966 9966. log₂(n!) is a bit less than n log₂ n.