# Kotlin Program to Find LCM of two Numbers

Kotlin Server Side ProgrammingProgramming

#### Kotlin Online Training

68 Lectures 4.5 hours

#### Kotlin Masterclass Programming: Android Coding Bible

71 Lectures 5.5 hours

#### Android Dependency Injection using Dagger with Kotlin

18 Lectures 1.5 hours

In this article, we will understand how to calculate the LCM of two numbers in Kotlin. Lowest Common Multiple (LCM) of two numbers is the smallest positive integer that is evenly divisible by both the numbers.

Below is a demonstration of the same

Suppose our input is

24 and 18


The desired output would be

The LCM of the two numbers is 72


## Algorithm

• Step 1 − Start

• Step 2 − Declare three integers: input1, input2 and myResult

• Step 3 − Define the values

• Step 4 − Using a while loop from 1 to the bigger number among the two inputs, check if the ‘i’ value divides both the inputs without leaving behind reminder.

• Step 5 - Display the ‘i’ value as LCM of the two numbers

• Step 6 - Stop

## Example 1

In this example, we will find the LCM of two numbers using while loop. First, declare and set the two inputs for which we will find the LCM later:

val input1 = 24
val input2 = 18


Also, set a variable for Result −

var myResult: Int


Now, use the while loop and get the LCM

myResult = if (input1 > input2) input1 else input2

while (true) {
if (myResult % input1 == 0 && myResult % input2 == 0) {
println("The LCM is $myResult.") break } ++myResult }  Let us now see the complete example − fun main() { val input1 = 24 val input2 = 18 var myResult: Int println("The input values are defined as$input1 and $input2") myResult = if (input1 > input2) input1 else input2 while (true) { if (myResult % input1 == 0 && myResult % input2 == 0) { println("The LCM is$myResult.")
break
}
++myResult
}
}


## Output

The input values are defined as 24 and 18
The LCM is 72.


## Example 2

In this example, we will find the LCM of two numbers

fun main() {
val input1 = 24
val input2 = 18
println("The input values are defined as $input1 and$input2")
getLCM(input1, input2)
}

fun getLCM(input1: Int, input2: Int){
var myResult: Int
myResult = if (input1 > input2) input1 else input2

while (true) {
if (myResult % input1 == 0 && myResult % input2 == 0) {
println("The LCM is \$myResult.")
break
}
++myResult
}
}


## Output

The input values are defined as 24 and 18
The LCM is 72.

Updated on 13-Oct-2022 12:42:32