简体   繁体   中英

What is the space complexity of a function that creates a variable of value `N!` (N factorial)?

The bit-length an integer of value N is O(lgN) .

What is the bit-length of an integer of value N! (ie 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 (ie 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 n! ~ c*sqrt(n)*n^n . Therefore, log(n!) ~ n*log(n) , which is the space complexity of n! .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM