Write a Kotlin Program to Find LCM of two Numbers

One of the fundamental concepts of mathematics is the Least Common Multiple (LCM).

In this tutorial, we will discuss how to find the LCM of two numbers using Kotlin.

Before diving into the program, let’s first understand what LCM is. LCM is the smallest positive integer that is divisible by both given numbers.

For example, the LCM of 6 and 8 is 24, as 24 is the smallest positive integer that is divisible by both 6 and 8.

Now, let’s write a Kotlin program to find the LCM of two numbers.

The program uses a simple algorithm to find the LCM.

fun main() {
    val num1 = 12
    val num2 = 18
    var lcm: Int

    // find the maximum of two numbers
    lcm = if (num1 > num2) num1 else num2

    // loop until lcm is found
    while (true) {
        if (lcm % num1 == 0 && lcm % num2 == 0) {
            println("The LCM of $num1 and $num2 is $lcm.")
            break
        }
        ++lcm
    }
}

In this program, we have two input numbers num1 and num2.

We have initialized lcm to 0. We then find the maximum of the two numbers using a simple if-else condition.

We start the loop to find the LCM. In each iteration, we check if the current lcm is divisible by both num1 and num2 using the modulo operator (%).

If it is, we print the LCM and break the loop. If not, we increment lcm by 1 and continue the loop until we find the LCM.

To test this program, you can change the values of num1 and num2 to your desired numbers. The program will then output the LCM of the two numbers.

In conclusion, finding the LCM of two numbers is a fundamental concept of mathematics that is frequently used in programming.

Kotlin provides a simple and efficient way to find the LCM using a while loop and the modulo operator.