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
# Python3 program to find the # Superfactorial of a number Â
# function to calculate the # value of Superfactorial def superfactorial(n): Â
    # initialise the     # val to 1     val = 1     ans = []     for i in range ( 1 , n + 1 ):         val = val * i         ans.append(val)     # ans is the list with     # all factorial till n.     arr = [ 1 ]     for i in range ( 1 , len (ans)):         arr.append((arr[ - 1 ] * ans[i])) Â
    return arr Â
# Driver Code n = 5 arr = superfactorial(n) print (arr[ - 1 ]) |
34560
Using built-in functions:
Time complexity: O(n)
Auxiliary Space: O(n)
Python3
import math Â
# Function to calculate the Superfactorial of a number def superfactorial(n):     # Initialize an empty list to store the factorials     factorials = []     # Use a loop to calculate the factorial of each number till n     for i in range ( 1 , n + 1 ):         factorials.append(math.factorial(i))     # Initialize the result to 1     result = 1     # Use a loop to compute the product of all factorials     for factorial in factorials:         result * = factorial     return result Â
# Test the function n = 5 print (superfactorial(n)) #This code is contributed by Edula Vinay Kumar Reddy |
34560
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)) Â
# Driver code n = 5 result = superfactorial(n) print (result) #this code is contributed by Jyothi Pinjala. |
34560
Time complexity: O(n)
Auxiliary Space: O(n)