In this tutorial you will learn about the C++ Programs to Find LCM of Two Numbers and its application with practical example.
In this tutorial, we will learn to create a c++ program that will find LCM of two numbers using c++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C ++ programming topics:
- Operators.
- Looping statements
- While loop.
- if else Statement.
- Basic input/output.
- Basic c++ programming.
What Is LCM?
LCM is a method to finding the smallest possible multiplication of two or more numbers. LCM of a numbers is divisible by both or more numbers. For example, LCM of 5 ,4 and 20 is 20.
C++ Programs to Find LCM of Two Numbers.
In this program you will learn to find LCM of two given number using while loop. We would first declared and initialized the required variables. Next, we would prompt user to input two numbers.Later we will find the or given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> using namespace std; int main() { int num1, num2, max; cout<<"Enter two positive integers: "; // taking two numbers cin>>num1>>num2; max = (num1 > num2) ? num1 : num2; // finding bigger number while (1) { if (max % num1 == 0 && max % num2 == 0) // condition for lcm { cout<<"The LCM of "<<num1<<" and "<<num2 <<" is "<<max; break; } ++max; } return 0; } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- num1 =It will hold first number given by user.
- num2 =It will hold second number given by user.
- max=This will find biggest among the number.
Let see the step by step method of finding LCM.
LCM of two given number, is as follows:
1: user will be prompted to enter two the positive integer values no1 and no2.
2: Storing the biggest value of num1 & num2 in max variable.3: On checking condition whether the max is divisible by both variables num1 and num2 loop will iterate until it will find a value which divisible by both number.
4: If variable max is divisible,Then display max as the LCM of these two numbers.
5: Else, the value of max is increased, and go to step 3 again and again.
6: Stop the program.
LCM stands for Least Common Multiple (LCM). It’s the smallest possible number that is completely divisible by both integer’s num1 and num2, without leaving any remainder means zero(0). It is also known as the Lowest Common Multiple.