C Program to find LCM of two numbers using Recursion
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
#include <stdio.h>
int Min( int Num1, int Num2)
{
return Num1 >= Num2
? Num2
: Num1;
}
int LCMUtil( int Num1, int Num2, int K)
{
if (Num1 == 1 || Num2 == 1)
return Num1 * Num2;
if (Num1 == Num2)
return Num1;
if (K <= Min(Num1, Num2)) {
if (Num1 % K == 0 && Num2 % K == 0) {
return K * LCMUtil(
Num1 / K, Num2 / K, 2);
}
else
return LCMUtil(Num1, Num2, K + 1);
}
else
return Num1 * Num2;
}
void LCM( int N, int M)
{
int lcm = LCMUtil(N, M, 2);
printf ( "%d" , lcm);
}
int main()
{
int N = 2, M = 4;
LCM(N, M);
return 0;
}
|
Time Complexity: O(max(N, M))
Auxiliary Space: O(1)
Last Updated :
15 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...