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:
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:
Explanation:
Functions:
- GCD Function:
- Uses the Euclidean algorithm to calculate the GCD.
- If
b
is zero,a
is the GCD. Otherwise, it calls itself recursively withb
anda % b
.
- LCM Function:
- Uses the formula mentioned earlier to calculate LCM based on the GCD.
- GCD Function:
Input:
- The program prompts the user to enter two integers.
Validation:
- It checks whether the input numbers are positive. If not, it prints a message and exits the program.
Calculations:
- The program calculates the GCD using the
gcd
function and then calculates the LCM using thelcm
function.
- The program calculates the GCD using the
Output:
- Finally, it prints the GCD and LCM of the two numbers.
Sample Output:
Example 1:
Example 2:
Example 3:
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.