Python | Superfactorial of a number.
Given a number, the task is to find the Superfactorial of a number. The result of multiplying the product of first n factorials is called Superfactorial of a number.
Superfactorial(n)= 1 ^ n * 2 ^ (n-1) * 3 ^ (n-2) * . . . . . * n ^ 1
Examples:
Input : 3
Output : 12 H(3) = 1! * 2! * 3! = 12
Input : 4
Output : 288 H(4) = 1^4 * 2^3 * 3^2 * 4^1 = 288
An efficient approach is to compute all factorial iteratively till n, then compute the product of all factorial till n.
Python3
def superfactorial(n):
val = 1
ans = []
for i in range ( 1 , n + 1 ):
val = val * i
ans.append(val)
arr = [ 1 ]
for i in range ( 1 , len (ans)):
arr.append((arr[ - 1 ] * ans[i]))
return arr
n = 5
arr = superfactorial(n)
print (arr[ - 1 ])
|
Using built-in functions:
Time complexity: O(n)
Auxiliary Space: O(n)
Python3
import math
def superfactorial(n):
factorials = []
for i in range ( 1 , n + 1 ):
factorials.append(math.factorial(i))
result = 1
for factorial in factorials:
result * = factorial
return result
n = 5
print (superfactorial(n))
|
Explanation: Using built-in math.factorial() function, we can calculate the factorial of each number till n and then compute the product of all factorials using a loop. This method is useful when we have to do many mathematical operations on large dataset.
Time-complexity:O(N) Since super-factorials of number can be huge, hence the numbers will overflow. We can use boost libraries in C++ or BigInteger in Java to store the super-factorial of a number N.
Auxiliary Space: O(N)
Using Recursion
Python3
import math
def superfactorial(n, acc = 1 ):
if n = = 1 :
return acc
else :
return superfactorial(n - 1 , acc * math.factorial(n))
n = 5
result = superfactorial(n)
print (result)
|
Time complexity: O(n)
Auxiliary Space: O(n)
Last Updated :
14 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...