Table of Contents

## Introduction

This program will help you find to find the LCM of two positive numbers.

The task is that the user will be asked to enter two integers, and then through this program, the LCM of both numbers will be computed.

**LCM**: Least Common Multiple.

A positive integer that is perfectly divisible by both numbers without leaving any remainder is the LCM of that number.

It is important to note that the LCM of both numbers cannot be less than the largest value among both numbers.

For example, the LCM of 12 and 36 is either 36 or greater than 36.

This logic will help us to build the program.

In this program, we will use the while loop and if statement to find the LCM.

To understand this example, you should know about some concepts of C++ programming.

1. Operators

2. if-else statement

3. while and do-while loop

4. Control statements: Go through the article on ‘break’ control statements in the C++ language series.

## Program

#include<iostream> using namespace std; int main() { int num1, num2; cout<<"Enter two positive numbers: "; cin>>num1>>num2; // find largest among num1 and num2 int largest; if (num1>num2) largest=num1; else largest=num2; // computation of LCM while(1) // condition always gives true { if (largest%num1==0 && largest%num2==0) { cout<<"LCM: "<<largest; break; // terminates the loop if LCM found } largest++; } return 0; }

## Output

## Explanation

In the above program, the user is asked to enter two positive integers, num1 and num2, and the values entered are 72 and 144, respectively.

**int largest; **

‘largest’ is the variable declared to store the maximum value among ‘num1’ and ‘num2.

Thus, the largest becomes 144.

Now we know LCM will be either 144 or greater than 144.

**while(1) **

using a while loop, we pass 1 so that it will always give the true result, and its body will execute.

**if (largest%num1==0 && largest%num2==0)**

since 144%72==0 and 144%144==0 are true, therefore the ‘if’ statement becomes true, and the value of ‘largest’ gets printed as LCM.

**break;**

The ‘break’ statement will terminate the loop, and the program exits.

If, in case, the ‘if’ statement becomes false, then its body won’t get executed, and then ‘largest’ is incremented.

## 0 Comments