GCD of factorials of two numbers
Last Updated :
15 Feb, 2023
Given two numbers m and n. Find the GCD of their factorial.
Examples :
Input : n = 3, m = 4
Output : 6
Explanation:
Factorial of n = 1 * 2 * 3 = 6
Factorial of m = 1 * 2 * 3 * 4 = 24
GCD(6, 24) = 6.
Input : n = 9, m = 5
Output : 20
Explanation:
Factorial of n = 1 * 2 * 3 *4 * 5 * 6 * 7 * 8 * 9 = 362880
Factorial of m = 1 * 2 * 3 * 4 * 5 = 120
GCD(362880, 120) = 120
A simple solution is to find factorials of both numbers. Then find GCD of the computed factorials.
An efficient solution is based on the fact that GCD of two factorials is equal to smaller factorial (note that factorials have all terms common).
Below is the implementation of above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int factorial( int x)
{
if (x <= 1)
return 1;
int res = 2;
for ( int i = 3; i <= x; i++)
res = res * i;
return res;
}
int gcdOfFactorial( int m, int n)
{
return factorial(min(m, n));
}
int main()
{
int m = 5, n = 9;
cout << gcdOfFactorial(m, n);
return 0;
}
|
Java
public class FactorialGCD{
static int factorial( int x)
{
if (x <= 1 )
return 1 ;
int res = 2 ;
for ( int i = 3 ; i <= x; i++)
res = res * i;
return res;
}
static int gcdOfFactorial( int m, int n)
{
int min = m < n ? m : n;
return factorial(min);
}
public static void main (String[] args)
{
int m = 5 , n = 9 ;
System.out.println(gcdOfFactorial(m, n));
}
}
|
Python
import math
def gcdOfFactorial(m, n) :
return math.factorial( min (m, n))
m = 5
n = 9
print (gcdOfFactorial(m, n))
|
C#
using System;
public class GFG{
static int factorial( int x)
{
if (x <= 1)
return 1;
int res = 2;
for ( int i = 3; i <= x; i++)
res = res * i;
return res;
}
static int gcdOfFactorial( int m, int n)
{
int min = m < n ? m : n;
return factorial(min);
}
public static void Main()
{
int m = 5, n = 9;
Console.WriteLine(gcdOfFactorial(m, n));
}
}
|
PHP
<?php
function factorial( $x )
{
if ( $x <= 1)
return 1;
$res = 2;
for ( $i = 3; $i <= $x ; $i ++)
$res = $res * $i ;
return $res ;
}
function gcdOfFactorial( $m , $n )
{
return factorial(min( $m , $n ));
}
$m = 5; $n = 9;
echo gcdOfFactorial( $m , $n );
?>
|
Javascript
<script>
function factorial(x) {
if (x <= 1)
return 1;
var res = 2;
for (i = 3; i <= x; i++)
res = res * i;
return res;
}
function gcdOfFactorial(m , n) {
var min = m < n ? m : n;
return factorial(min);
}
var m = 5, n = 9;
document.write(gcdOfFactorial(m, n));
</script>
|
Time complexity: O(min(m,n))
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...