C program to find LCM of two numbers using recursion

Write a C program to find LCM(Least Common Multiple) of two numbers using recursion. How to find LCM of two given numbers in C programming using recursion. Recursive function to find LCM of two given numbers.

Input first number: 12
Input second number: 30
Output LCM: 60

Required knowledge

Basic C programming, Function, Recursion

Logic to find LCM of two numbers using recursion

We have already seen in one of my previous posts about, what is LCM and how to find LCM of two numbers using loop. If you haven't gone through my previous post please go through so that you can get the basic idea of calculating LCM.
LCM of two numbers
Here we will just convert the iterative method of finding LCM into recursive method. Finding LCM using iterative method involves three basic steps:
  1. Initialize the multiple variable with the maximum value among two given numbers.
  2. Check whether the multiple clearly divides both the number or not. If it does, then end the process and return the multiple as the LCM.
  3. If multiple doesn't clearly divides both given numbers then increment the multiple by the max values among both the given numbers.
Repeat steps 2-3 till you find lcm. To convert the above iterative approach of finding LCM into recursive we will use step 2 as our base condition.

Program to find LCM using recursion

 * C program to find LCM of two numbers using recursion
#include <stdio.h>

/* Function declaration */
int lcm(int a, int b);

int main()
    int num1, num2, LCM;

    //Reads two numbers from user
    printf("Enter any two numbers to find lcm: ");
    scanf("%d%d", &num1, &num2);
     * Ensures that first parameter of lcm function is always less than second
    if(num1 > num2)
        LCM = lcm(num2, num1);
        LCM = lcm(num1, num2);
    printf("LCM of %d and %d = %d\n", num1, num2, LCM);
    return 0;

 * Recursive function to find lcm of two numbers 'a' and 'b'.
 * Here 'a' needs to be always less than 'b'.
int lcm(int a, int b)
    static int multiple = 0;
    //Increments multiple by adding max value to it
    multiple += b;
     * Base condition of recursion
     * If found a common multiple then return the multiple.
    if((multiple % a == 0) && (multiple % b == 0))
        return multiple;
        return lcm(a, b);

Note: Since we don't want the variable multiple to be reinitialized again and again by recursive function calls, therefore I have used static int multiple = 0;.

Also you can remove the other condition as it is not necessary. Means you can simply write the if statement as if(multiple % a == 0). Since the variable multiple is always a multiple of b.

Enter any two numbers to find lcm: 12
LCM of 12 and 30 = 60

Happy coding ;)

You may also like

Labels: , , , , ,