LCM of digits of a given number

2

Given a number n, find 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.

We traverse the digits of number one by one below loop

digit = n mod 10;
n = n / 10;

While traversing digits, we keep track of current LCM and keep updating LCM by finding LCM of current digit with current LCM.

// CPP program to find LCM of digits of a number
#include<iostream>
#include<boost/math/common_factor.hpp>
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;
}

Output:

63

This article is contributed by nikunj_agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



2 Average Difficulty : 2/5.0
Based on 1 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.