📜  给定数字的数字的LCM

📅  最后修改于: 2021-04-29 04:19:33             🧑  作者: Mango

给定数字n,找到其数字的LCM。
例子:

Input : 397
Output : 63
LCM of 3, 9 and 7 is 63.

Input : 244
Output : 4
LCM of 2, 4 and 4 is 4.

我们在循环下面逐一遍历数字
digit = n mod 10;
n = n / 10;
在遍历数字时,我们会跟踪当前LCM,并通过使用当前LCM查找当前数字的LCM来不断更新LCM。

C++
// CPP program to find LCM of digits of a number
#include
#include
using namespace std;
 
int digitLCM(int n)
{
    int lcm = 1;
    while (n > 0)
    {
        lcm = boost::math::lcm(n%10, lcm);
 
        // If at any point LCM become 0.
        // return it
        if (lcm == 0)
            return 0;
 
        n = n/10;
    }
    return lcm;
}
 
// driver code
int main()
{
    long n = 397;
    cout << digitLCM(n);
    return 0;
}


Java
// Java program to find LCM of digits of a number
 
class GFG
{
// define lcm function
static int lcm_fun(int a, int b)
{
    if (b == 0)
        return a;
    return lcm_fun(b, a % b);
}
 
static int digitLCM(int n)
{
    int lcm = 1;
    while (n > 0)
    {
        lcm = (n % 10 * lcm) / lcm_fun(n % 10, lcm);
 
        // If at any point LCM become 0.
        // return it
        if (lcm == 0)
            return 0;
 
        n = n/10;
    }
    return lcm;
}
 
// driver code
public static void main(String[] args)
{
    int n = 397;
    System.out.println(digitLCM(n));
}
}
// This code is contributed by mits


Python3
# Python3 program to find
# LCM of digits of a number
 
# define lcm function
def lcm_fun(a, b):
 
    if (b == 0):
        return a;
    return lcm_fun(b, a % b);
 
def digitLCM(n):
 
    lcm = 1;
    while (n > 0):
        lcm = int((n % 10 * lcm) /
              lcm_fun(n % 10, lcm));
 
        # If at any point LCM
        # become 0. return it
        if (lcm == 0):
            return 0;
 
        n = int(n / 10);
     
    return lcm;
 
# Driver code
n = 397;
print(digitLCM(n));
 
# This code is contributed by mits


C#
// C# program to find LCM of digits
// of a number
class GFG
{
     
// define lcm function
static int lcm_fun(int a, int b)
{
    if (b == 0)
        return a;
    return lcm_fun(b, a % b);
}
 
static int digitLCM(int n)
{
    int lcm = 1;
    while (n > 0)
    {
        lcm = (n % 10 * lcm) / lcm_fun(n % 10, lcm);
 
        // If at any point LCM become 0.
        // return it
        if (lcm == 0)
            return 0;
 
        n = n/10;
    }
    return lcm;
}
 
// Driver Code
public static void Main()
{
    int n = 397;
    System.Console.WriteLine(digitLCM(n));
}
}
 
// This code is contributed by mits


PHP
 0)
    {
        $lcm = (int)(($n % 10 * $lcm) /
              lcm_fun($n % 10, $lcm));
 
        // If at any point LCM
        // become 0. return it
        if ($lcm == 0)
            return 0;
 
        $n = (int)($n / 10);
    }
    return $lcm;
}
 
// Driver code
$n = 397;
echo digitLCM($n);
 
// This code is contributed by mits
?>


Javascript


输出:

63