C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

LCM using Recursive function

LCM using a Recursive Function, based on the relationship between GCD and LCM.

C Program: LCM using Recursive Function

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");

        return 0;

    }

 

    // Function call

    result = lcm(num1, num2);

 

    // Display result

    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 GCD

int lcm(int a, int b) {

    return (a * b) / gcd(a, b);  // Formula-based relation

}

Output

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

OUTPUT 2 :
Enter two positive integers: 5 7
LCM of 5 and 7 is 35

Explanation

  1. Mathematical Formula Used

 C Programs

  1. Recursive GCD Function
    • Uses the Euclidean algorithm:
  • gcd(a, b) = gcd(b, a % b)

until b becomes 0.

  1. LCM Function
    • Calls the gcd() function and computes LCM using the formula above.

Example (for 12 and 18)

gcd(12, 18)

→ gcd(18, 12)

→ gcd(12, 6)

→ gcd(6, 0)

→ return 6

 

lcm = (12 × 18) / 6 = 36