LCM (Least Common Multiple) and GCD (Greatest Common Divisor) are two important concepts in number theory. Here's a brief explanation of both:

  • GCD: The largest positive integer that divides two or more integers without leaving a remainder.
  • LCM: The smallest positive integer that is divisible by both of the given integers.

Relationship Between GCD and LCM

There is a relationship between GCD and LCM given by the formula:

LCM(a,b)=a×bGCD(a,b)\text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)}

This formula allows you to calculate LCM using GCD.

C Program to Calculate GCD and LCM

Here’s a C program that calculates both the GCD and LCM of two integers:

#include <stdio.h> // Function to calculate GCD int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); // Recursive call } // Function to calculate LCM using GCD int lcm(int a, int b) { return (a * b) / gcd(a, b); } int main() { int num1, num2; // Input two numbers from the user printf("Enter two integers: "); scanf("%d %d", &num1, &num2); // Ensure that the input is positive if (num1 <= 0 || num2 <= 0) { printf("Please enter positive integers.\n"); return 1; // Exit the program with an error code } // Calculate GCD and LCM int gcdResult = gcd(num1, num2); int lcmResult = lcm(num1, num2); // Output the results printf("GCD of %d and %d is: %d\n", num1, num2, gcdResult); printf("LCM of %d and %d is: %d\n", num1, num2, lcmResult); return 0; }

Explanation:

  1. Functions:

    • GCD Function:
      • Uses the Euclidean algorithm to calculate the GCD.
      • If b is zero, a is the GCD. Otherwise, it calls itself recursively with b and a % b.
    • LCM Function:
      • Uses the formula mentioned earlier to calculate LCM based on the GCD.
  2. Input:

    • The program prompts the user to enter two integers.
  3. Validation:

    • It checks whether the input numbers are positive. If not, it prints a message and exits the program.
  4. Calculations:

    • The program calculates the GCD using the gcd function and then calculates the LCM using the lcm function.
  5. Output:

    • Finally, it prints the GCD and LCM of the two numbers.

Sample Output:

Example 1:

Enter two integers: 12 15 GCD of 12 and 15 is: 3 LCM of 12 and 15 is: 60

Example 2:

Enter two integers: 18 24 GCD of 18 and 24 is: 6 LCM of 18 and 24 is: 72

Example 3:

Enter two integers: 10 0 Please enter positive integers.

Key Points:

  • GCD Calculation: The GCD function is efficient and leverages recursion.
  • LCM Calculation: The relationship between GCD and LCM simplifies the LCM calculation.
  • Input Validation: The program includes a simple validation step to ensure positive input.
  • Modularity: The separation of GCD and LCM into different functions enhances code readability and reusability.