LCM of factorial and its neighbors
Last Updated :
23 Jun, 2022
Given a number, we need to find LCM of the factorial of the numbers and its neighbors. If the number is N, we need to find LCM of (N-1)!, N! and (N+1)!.Here N is always greater than or equal too 1
Examples :
Input : N = 5
Output : 720
Explanation
Here the given number is 5, its neighbors
are 4 and 6. The factorial of these three
numbers are 24, 120, and 720.so the LCM
of 24, 120, 720 is 720.
Input : N = 3
Output : 24
Explanation
Here the given number is 3, its Neighbors
are 2 and 4.the factorial of these three
numbers are 2, 6, and 24. So the LCM of
2, 6 and 24 is 24.
Method 1(Simple). We first calculate the factorial of number and the factorial of its neighbor then
find the LCM of these factorials numbers.
Method 2(Efficient)
We can see that the LCM of (N-1)!, N! and (N+1)! is always (N-1)! * N! * (N+1)!
this can be written as (N-1)! * N*(N-1)! * (N+1)*N*(N-1)!
so the LCM become (N-1)! * N * (N+1)
which is (N+1)!
Example
N = 5
We need to find the LCM of 4!, 5!and 6!
LCM of 4!, 5!and 6!
= 4! * 5! * 6!
= 4! * 5*4! * 6*5*4!
= 6*5*4!
= 720
So we can say that LCM of the factorial of three consecutive numbers is always the factorial of the largest number.in this case (N+1)!.
C++
#include <bits/stdc++.h>
using namespace std;
unsigned int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int LCMOfNeighbourFact( int n)
{
return factorial(n + 1);
}
int main()
{
int N = 5;
cout << LCMOfNeighbourFact(N) << "\n" ;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int factorial( int n)
{
if (n == 0 )
return 1 ;
return n * factorial(n - 1 );
}
static int LCMOfNeighbourFact( int n)
{
return factorial(n + 1 );
}
public static void main(String args[])
{
int N = 5 ;
System.out.println(LCMOfNeighbourFact(N));
}
}
|
Python3
def factorial(n):
if (n = = 0 ):
return 1
return n * factorial(n - 1 )
def LCMOfNeighbourFact(n):
return factorial(n + 1 )
N = 5
print (LCMOfNeighbourFact(N))
|
C#
using System;
class GFG
{
static int factorial( int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
static int LCMOfNeighbourFact( int n) {
return factorial(n + 1);
}
public static void Main()
{
int N = 5;
Console.WriteLine(LCMOfNeighbourFact(N));
}
}
|
PHP
<?php
function factorial( $n )
{
if ( $n == 0)
return 1;
return $n * factorial( $n - 1);
}
function LCMOfNeighbourFact( $n )
{
return factorial( $n + 1);
}
$N = 5;
echo (LCMOfNeighbourFact( $N ));
?>
|
Javascript
<script>
function factorial(n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
function LCMOfNeighbourFact(n)
{
return factorial(n + 1);
}
var N = 5;
document.write(LCMOfNeighbourFact(N));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Please suggest if someone has a better solution which is more efficient in terms of space and time.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...