Example:
Input first number: 12
Input second number: 30
Output LCM: 60
Required knowledge
Basic C programming, Function, RecursionLogic 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.- Initialize the multiple variable with the maximum value among two given numbers.
- 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.
- If multiple doesn't clearly divides both given numbers then increment the multiple by the max values among both the given numbers.
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); else 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; } else { 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.
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.
Output
Enter any two numbers to find lcm: 12
30
LCM of 12 and 30 = 60
30
LCM of 12 and 30 = 60
Happy coding ;)
You may also like
- Function and recursion programming exercises index.
- C program to find GCD(HCF) of any two numbers using loop.
- C program to display elements of array using recursion.
- C program to find sum of all elements of an array using recursion.
- C program to find factorial of any number using recursion.
- C program to find fibonacci series up to n terms.
- C program to find reverse of any number using recursion.
- C program to check palindrome numbers using recursion.
- C program to find sum of all even or odd numbers using recursion.
- C program to check prime, armstrong and perfect numbers using functions .