Given two integers N and M, the task is to find their LCM using recursion.
Examples:
Input: N = 2, M = 4
Output: 4
Explanation: LCM of 2, 4 is 4.Input: N = 3, M = 5
Output: 15
Explanation: LCM of 3, 5 is 15.
Approach: The idea is to use the basic elementary method of finding LCM of two numbers. Follow the steps below to solve the problem:
- Define a recursive function LCM() with 3 integer parameters N, M, and K to find LCM of N and M.
- The following base conditions need to be considered:
- If N or M is equal to 1, return N * M.
- If N is equal to M, return N.
- If K < min(N, M):
- If K divides both N and M, return K * LCM(N/K, M/K, 2).
- Otherwise, increment K by 1 and return LCM(N, M, K+1).
- Otherwise, return the product of N and M.
- Finally, print the result of the recursive function as the required LCM.
Below is the implementation of the above approach:
C
// C program for the above approach#include <stdio.h>// Function to return the// minimum of two numbersintMin(intNum1,intNum2){returnNum1 >= Num2? Num2: Num1;}// Utility function to calculate LCM// of two numbers using recursionintLCMUtil(intNum1,intNum2,intK){// If either of the two numbers// is 1, return their productif(Num1 == 1 || Num2 == 1)returnNum1 * Num2;// If both the numbers are equalif(Num1 == Num2)returnNum1;// If K is smaller than the// minimum of the two numbersif(K <= Min(Num1, Num2)) {// Checks if both numbers are// divisible by K or notif(Num1 % K == 0 && Num2 % K == 0) {// Recursively call LCM() functionreturnK * LCMUtil(Num1 / K, Num2 / K, 2);}// OtherwiseelsereturnLCMUtil(Num1, Num2, K + 1);}// If K exceeds minimumelsereturnNum1 * Num2;}// Function to calculate LCM// of two numbersvoidLCM(intN,intM){// Stores LCM of two numberintlcm = LCMUtil(N, M, 2);// Print LCMprintf("%d", lcm);}// Driver Codeintmain(){// Given N & MintN = 2, M = 4;// Function CallLCM(N, M);return0;}Output:4
Time Complexity: O(max(N, M))
Auxiliary Space: O(1)Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


