Exponential factorial of N
Last Updated :
15 Dec, 2022
Given a positive integer N, the task is to print the Exponential factorial of N. Since the output can be very large, print the answer modulus 1000000007.
Examples:
Input: N = 4
Output: 262144
Input: N = 3
Output: 9
Approach: The given problem can be solved based on the following observations:
The exponential factorial is defined by the recurrence relation:
- .
Follow the steps below to solve the problem:
- Initialize a variable say res as 1 to store the exponential factorial of N.
- Iterate over the range [2, N] using the variable i and in each iteration update the res as res = ires%1000000007.
- Finally, after completing the above step, print the answer obtained in res.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int ExpoFactorial( int N)
{
int res = 1;
int mod = 1000000007;
for ( int i = 2; i < N + 1; i++)
res = ( int ) pow (i, res) % mod;
return res;
}
int main()
{
int N = 4;
cout << (ExpoFactorial(N));
return 0;
}
|
Java
import java.io.*;
class GFG{
static int ExpoFactorial( int N)
{
int res = 1 ;
int mod = 1000000007 ;
for ( int i = 2 ; i < N + 1 ; i++)
res = ( int )Math.pow(i, res) % mod;
return res;
}
public static void main(String[] args)
{
int N = 4 ;
System.out.println((ExpoFactorial(N)));
}
}
|
Python3
def ExpoFactorial(N):
res = 1
mod = ( int )( 1000000007 )
for i in range ( 2 , N + 1 ):
res = pow (i, res, mod)
return res
N = 4
print (ExpoFactorial(N))
|
C#
using System;
class GFG{
static int ExpoFactorial( int N)
{
int res = 1;
int mod = 1000000007;
for ( int i = 2; i < N + 1; i++)
res = ( int )Math.Pow(i, res) % mod;
return res;
}
public static void Main()
{
int N = 4;
Console.Write(ExpoFactorial(N));
}
}
|
Javascript
<script>
function ExpoFactorial(N) {
let res = 1;
let mod = 1000000007;
for (let i = 2; i < N + 1; i++)
res = Math.pow(i, res) % mod;
return res;
}
let N = 4;
document.write((ExpoFactorial(N)));
</script>
|
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...