C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

LCM using GCD Recursive function

LCM (Least Common Multiple) using the GCD function — a common and efficient mathematical approach.

C Program: Find LCM using GCD (Recursion)

C

#include <stdio.h>

 

// Function declarations

int gcd(int a, int b);

int lcm(int a, int b);

 

int main() {

    int num1, num2, result;

 

    // Input two positive integers

    printf("Enter two positive integers: ");

    scanf("%d %d", &num1, &num2);

 

    // Validate input

    if (num1 <= 0 || num2 <= 0) {

        printf("Please enter positive integers only.\n");

    } else {

        result = lcm(num1, num2);  // Function call

        printf("LCM of %d and %d is %d\n", num1, num2, result);

    }

 

    return 0;

}

 

// Recursive function to find GCD

int gcd(int a, int b) {

    if (b == 0)

        return a;          // Base case

    else

        return gcd(b, a % b);  // Recursive call

}

 

// Function to find LCM using the GCD

int lcm(int a, int b) {

    return (a * b) / gcd(a, b);

}

Output

 
OUTPUT :
Enter two positive integers: 12 18
LCM of 12 and 18 is 36

Explanation

  1. Mathematical Formula Used

C Programs

  1. Steps:
    • The program first finds the GCD using recursion.
    • Then it calculates LCM using the formula above.
  2. Why use GCD?
    • It’s efficient and avoids repeated iteration or multiple loops.