The bit-length an integer of value N
is O(lgN)
.
What is the bit-length of an integer of value N!
(i.e. N
factorial)? If a function gets passed in a list of length N
and it creates a variable of value N!
, what is the space complexity of the function?
Example function:
def numPermutations(nums):
'''Precondition: `nums` is a list of distinct numbers'''
N = len(nums)
return math.factorial(N)
Would the function have O(1)
space complexity since it creates only one integer variable (i.e. N
) and it's conceivable that the a sensible implementation of math.factorial
would also only create at most a couple integer variables? Or would it be O(lgN!)
since the bit-length of N!
is on the order of lg2(N!)
?
(Side note: lg2(N!) ==
sum from i = 1
to N
of lg2(i)
.)
I coded the following to create some data:
from math import factorial
for N in range(100):
print(f'{N}, {factorial(N).bit_length()}')
The data is visualized in this Desmos: Bit-length of N!. The Desmos also includes a few functions/regressions that match the data.
According to Stirling's formula, you can assume n! ~ c*sqrt(n)*n^n
. Therefore, log(n!) ~ n*log(n)
, which is the space complexity of n!
.