两个数的阶乘的GCD

给定两个数m和n,求其阶乘的GCD。 例如:

null
Input : n = 3, m = 4Output : 6Explanation:Factorial of n = 1 * 2 * 3 = 6Factorial of m = 1 * 2 * 3 * 4 = 24GCD(6, 24) = 6.Input : n = 9, m = 5Output : 20Explanation:Factorial of n = 1 * 2 * 3 *4 * 5 * 6 * 7 * 8 * 9 = 362880Factorial of m = 1 * 2 * 3 * 4 * 5 = 120GCD(362880, 120) = 120

A. 简单解决方案 就是找到 阶乘 这两个数字都有。然后找到 GCD 计算出的阶乘。 一 有效解决方案 基于两个阶乘的GCD等于较小的阶乘这一事实(请注意,阶乘具有所有公共项)。 下面是上述方法的实现。

C++

// CPP program to find GCD of factorial of two
// numbers.
#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

// Java program to find GCD of factorial
// of two numbers.
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);
}
/* Driver program to test above functions */
public static void main (String[] args)
{
int m = 5 , n = 9 ;
System.out.println(gcdOfFactorial(m, n));
}
}
// This code is contributed by Prerna Saini


python

# Python code to find GCD of factorials of
# two numbers.
import math
def gcdOfFactorial(m, n) :
return math.factorial( min (m, n))
# Driver code
m = 5
n = 9
print (gcdOfFactorial(m, n))


C#

// C# program to find GCD of factorial
// of two numbers.
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);
}
/* Driver program to test above functions */
public static void Main()
{
int m = 5, n = 9;
Console.WriteLine(gcdOfFactorial(m, n));
}
}
// This code is contributed by Anant Agarwal.


PHP

<?php
// PHP program to find GCD
// of factorial of two numbers.
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 ));
}
// Driver Code
$m = 5; $n = 9;
echo gcdOfFactorial( $m , $n );
// This code is contributed by ajit
?>


Javascript

<script>
// JavaScript program to find GCD of factorial
// of two numbers.
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);
}
/* Driver program to test above functions */
var m = 5, n = 9;
document.write(gcdOfFactorial(m, n));
// This code is contributed by aashish1995
</script>


输出:

120

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享