Find the next Factorial greater than N
Last Updated :
26 Nov, 2021
Given a number N (? 1018), the task is to find the next factorial number greater than N.
Examples:
Input: N = 24
Output: 120
Explanation:
As 4! = 24. So the next number which factorial and greater than 24 is 5!, which is 120
Input: N = 150
Output: 720
Explanation:
As 5! = 120. So the next number which factorial and greater than 150 is 6!, which is 720.
Approach:
- Precompute the factorial of all number upto 20 in an array as 20! > 1018.
- Traverse the factorial array and find the value which is just greater than N as the required next factorial number.
Below is the implementation of above approach:
C++
#include "bits/stdc++.h"
using namespace std;
long long fact[21];
void preCompute()
{
fact[0] = 1;
for ( int i = 1; i < 18; i++)
fact[i] = (fact[i - 1] * i);
}
void nextFactorial( int N)
{
for ( int i = 0; i < 21; i++) {
if (N < fact[i]) {
cout << fact[i];
break ;
}
}
}
int main()
{
preCompute();
int N = 120;
nextFactorial(N);
return 0;
}
|
Java
class GFG {
final static int fact[] = new int [ 21 ];
static void preCompute()
{
fact[ 0 ] = 1 ;
for ( int i = 1 ; i < 18 ; i++)
fact[i] = (fact[i - 1 ] * i);
}
static void nextFactorial( int N)
{
for ( int i = 0 ; i < 21 ; i++) {
if (N < fact[i]) {
System.out.println(fact[i]);
break ;
}
}
}
public static void main (String[] args)
{
preCompute();
int N = 120 ;
nextFactorial(N);
}
}
|
Python3
fact = [ 0 ] * 21
def preCompute():
fact[ 0 ] = 1
for i in range ( 1 , 18 ):
fact[i] = (fact[i - 1 ] * i)
def nextFactorial(N):
for i in range ( 21 ):
if N < fact[i]:
print (fact[i])
break
preCompute()
N = 120
nextFactorial(N)
|
C#
using System;
class GFG {
static int []fact = new int [21];
static void preCompute()
{
fact[0] = 1;
for ( int i = 1; i < 18; i++)
fact[i] = (fact[i - 1] * i);
}
static void nextFactorial( int N)
{
for ( int i = 0; i < 21; i++) {
if (N < fact[i]) {
Console.WriteLine(fact[i]);
break ;
}
}
}
public static void Main ( string [] args)
{
preCompute();
int N = 120;
nextFactorial(N);
}
}
|
Javascript
<script>
fact = Array(21).fill(0);
function preCompute()
{
fact[0] = 1;
for ( var i = 1; i < 18; i++)
fact[i] = (fact[i - 1] * i);
}
function nextFactorial(N)
{
for ( var i = 0; i < 21; i++) {
if (N < fact[i]) {
document.write(fact[i]);
break ;
}
}
}
preCompute();
var N = 120;
nextFactorial(N);
</script>
|
Time Complexity: O(21)
Auxiliary Space: O(21)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...