LCM of digits of a given number
Last Updated :
26 Dec, 2022
Given a number n, find the LCM of its digits.
Examples:
Input : 397
Output : 63
LCM of 3, 9 and 7 is 63.
Input : 244
Output : 4
LCM of 2, 4 and 4 is 4.
Method 1:
Follow the steps to solve this problem:
- Initialise a variable l = 1
- While n is greater than 0. Do the following:
- Find the LCM of n % 10 and lcm
- Check if lcm == 0 , return 0
- Initialise n = n / 10;
- Finally, return l.
Follow the steps below to implement the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long gcd( long long int a, long long int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
long long lcm( int a, int b) { return (a / gcd(a, b)) * b; }
int digitLCM( int n)
{
int l = 1;
while (n > 0) {
l = lcm(n % 10, l);
if (lcm == 0)
return 0;
n = n / 10;
}
return l;
}
int main()
{
long n = 397;
cout << digitLCM(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
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 (lcm == 0 )
return 0 ;
n = n/ 10 ;
}
return lcm;
}
public static void main(String[] args)
{
int n = 397 ;
System.out.println(digitLCM(n));
}
}
|
Python3
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 (lcm = = 0 ):
return 0 ;
n = int (n / 10 );
return lcm;
n = 397 ;
print (digitLCM(n));
|
C#
class GFG
{
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 (lcm == 0)
return 0;
n = n/10;
}
return lcm;
}
public static void Main()
{
int n = 397;
System.Console.WriteLine(digitLCM(n));
}
}
|
PHP
<?php
function lcm_fun( $a , $b )
{
if ( $b == 0)
return $a ;
return lcm_fun( $b , $a % $b );
}
function digitLCM( $n )
{
$lcm = 1;
while ( $n > 0)
{
$lcm = (int)(( $n % 10 * $lcm ) /
lcm_fun( $n % 10, $lcm ));
if ( $lcm == 0)
return 0;
$n = (int)( $n / 10);
}
return $lcm ;
}
$n = 397;
echo digitLCM( $n );
?>
|
Javascript
<script>
function lcm_fun( a, b)
{
if (b == 0)
return a;
return lcm_fun(b, a % b);
}
function digitLCM( n)
{
let lcm = 1;
while (n > 0)
{
lcm = (n % 10 * lcm) / lcm_fun(n % 10, lcm);
if (lcm == 0)
return 0;
n = parseInt(n / 10);
}
return lcm;
}
let n = 397;
document.write(digitLCM(n));
</script>
|
Time Complexity: O(log n), the time complexity of this algorithm is O(log n) as we are making a single iteration and each iteration is taking O(1) time for computation.
Auxiliary Space: O(1), the space complexity of this algorithm is O(1) as we are using a single variable l to store the lcm of the digits.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...