C Program to Find LCM of a Number using Recursion

«
»

This is a C Program to find lcm of a number using recursion.

Problem Description

This C Program Finds LCM of a Number using Recursion.

Problem Solution

The following C program, using recursion, finds the LCM. An LCM is the lowest common multiple of any 2 numbers.

advertisement
Program/Source Code

Here is the source code of the C program to find LCM of a Number using Recursion. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C Program to Find LCM of a Number using Recursion
 */
#include <stdio.h>
 
int lcm(int, int);
 
int main()
{
    int a, b, result;
    int prime[100];
 
    printf("Enter two numbers: ");
    scanf("%d%d", &a, &b);
    result = lcm(a, b);
    printf("The LCM of %d and %d is %d\n", a, b, result);
    return 0;
}
 
int lcm(int a, int b)
{ 
    static int common = 1;
 
    if (common % a == 0 && common % b == 0)
    {
        return common;
    }
    common++;
    lcm(a, b);
    return common;
}
Program Explanation

In this C program, we are reading the two integer numbers using ‘a’ and ‘b’ variables respectively. The lcm() function is used to find LCM of a number using recursion.

advertisement

Assign the value of ‘common’ variable as 1. If condition statement is used to check the modulus of the value of ‘common’ variable by the value of ‘a’ variable is equal to 0. Also the modulus of the value of ‘common’ variable by the value of ‘b’ variable is equal to 0 using AND operation. If the condition is true, then execute the statement and return the ‘common’ value. Print the LCM of a number using the printf statement.

Runtime Test Cases
 
$ cc pgm22.c
$ a.out
Enter two numbers: 456
12
The LCM of 456 and 12 is 456
 
$ a.out
Enter two numbers: 45 75
The LCM of 45 and 75 is 225

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Mathematical Functions, go to C Programming Examples on Mathematical Functions. If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn