Write a C program to enter two numbers and find LCM (Lowest Common Multiple) using for loop. How to find LCM of two given numbers in C programming. Logic to find LCM of two number in C program.
Example
Input
Input number1: 12 Input number2: 30
Output
LCM = 60
Required knowledge
Basic C programming, If else, Conditional operator, For loop
What is LCM (Lowest Common Multiple)?
LCM is the smallest positive integer that exactly divides two or more numbers. For Example
Logic to find LCM of two numbers
Before I get deep in the logic to find LCM. You must know how to check divisibility of any number.
To make things simple and generic, I have divided the logic in four steps. Below is the descriptive logic to find LCM.
- Find maximum between two numbers. Say max contains maximum between two numbers to find lcm. Maximum is used to generate next multiple which must be common to both.
- If max is exactly divisible by both numbers. Then you got your answer, lcm of two numbers is max.
- If you did not got your answer in previous step. Then generate next multiple of max.
- Repeat 2-3 step till lcm is not found.
Program to find LCM of two numbers
/** * C program to find LCM of any two numbers */ #include <stdio.h> int main() { int i, num1, num2, max, lcm=1; /* * Read two numbers from user */ printf("Enter any two numbers to find LCM: "); scanf("%d%d", &num1, &num2); // Find maximum between num1 and num2 max = (num1 > num2) ? num1 : num2; // First multiple to be checked for common i = max; //Loop runs forever till lcm is not found while(1) { if(i%num1==0 && i%num2==0) { /* * If i divides both num1 and num2 * then lcm is found hence exit from loop */ lcm = i; break; } /* * If lcm is not found then generate next * multiple of max between both numbers */ i += max; } printf("LCM of %d and %d = %d", num1, num2, lcm); return 0; }
Note: Do not confuse with the statement max = (num1 > num2) ? num1 : num2;. It finds maximum between two numbers. Read more about finding maximum using conditional operator.
Before you move to next exercise or program. I strongly recommend you to learn the program using recursive approach.
Enter any two numbers to find LCM: 12 30 LCM of 12 and 30 = 60
Happy coding ;)
Recommended posts
- Loop programming exercises index.
- C program to find HCF of two numbers.
- C program to print all factors of number.
- C program to print all Prime factors of a number.
- C program to find factorial of any number.
- C program to print table of any number in proper format.
- C program to enter P, T, R and calculate Compound Interest.