C Program to find LCM of two numbers

LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers.

For example LCM of 15 and 20 is 60 and LCM of 5 and 7 is 35.

LCM of two numbers ‘a’ and ‘b’ can be calculated using following formula.

   a x b = LCM(a, b) * GCD (a, b)

   LCM(a, b) = (a x b) / GCD(a, b) 

We have discussed function to find GCD of two numbers. Using GCD, we can find LCM.

Following is implementation of above idea.

C

#include <stdio.h>

// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    // base case
    if (a == b)
        return a;

    // a is greater
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}

// Function to return LCM of two numbers
int lcm(int a, int b)
{
    return (a*b)/gcd(a, b);
}

// Driver program to test above function
int main()
{
    int a = 15, b = 20;
    printf("LCM of %d and %d is %d ", a, b, lcm(a, b));
    return 0;
}

Java

// Java program to find factorial of given number
class Test
{
	// Recursive method to return gcd of a and b
	static int gcd(int a, int b)
	{
	    // Everything divides 0 
	    if (a == 0 || b == 0)
	       return 0;
	 
	    // base case
	    if (a == b)
	        return a;
	 
	    // a is greater
	    if (a > b)
	        return gcd(a-b, b);
	    return gcd(a, b-a);
	}
	
	// method to return LCM of two numbers
	static int lcm(int a, int b)
	{
	    return (a*b)/gcd(a, b);
	}
	
    // Driver method
    public static void main(String[] args) 
    {
    	int a = 15, b = 20;
        System.out.println("LCM of " + a +" and " + b + " is " + lcm(a, b));
    }
}

Output:

LCM of 15 and 20 is 60

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:







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