Kotlin Program to Find LCM of two Numbers

The LCM of two integers is the smallest positive integer that is perfectly divisible by both the numbers (without a remainder).

Example 1: Kotlin Program to calculate LCM using while Loop and if Statement

fun main(args: Array<String>) {
    val n1 = 72
    val n2 = 120
    var lcm: Int

    // maximum number between n1 and n2 is stored in lcm
    lcm = if (n1 > n2) n1 else n2

    // Always true
    while (true) {
        if (lcm % n1 == 0 && lcm % n2 == 0) {
            println("The LCM of $n1 and $n2 is $lcm.")
            break
        }
        ++lcm
    }
}

When you run the program, the output will be:

The LCM of 72 and 120 is 360.

In this program, the two numbers whose LCM is to be found are stored in variables n1 and n2 respectively.

Then, we initially set lcm to the largest of the two numbers. This is because, LCM cannot be less than the largest number.

Similar to Java, inside the infinite while loop (while(true)), we check if lcm perfectly divides both n1 and n2 or not.

If it does, we've found the LCM. We print the LCM and break out from the while loop using break statement.

Else, we increment lcm by 1 and re-test the divisibility condition.

Here's the equivalent Java code: Java Program to Find LCM of two Numbers.


We can also use GCD to find the LCM of two numbers using the following formula:

LCM = (n1 * n2) / GCD

If you don't know how to calculate GCD in Java, check Kotlin Program to find GCD of two numbers.

Example 2: Kotlin Program to Calculate LCM using GCD

fun main(args: Array<String>) {
    val n1 = 72
    val n2 = 120
    var gcd = 1

    var i = 1
    while (i <= n1 && i <= n2) {
        // Checks if i is factor of both integers
        if (n1 % i == 0 && n2 % i == 0)
            gcd = i
        ++i
    }

    val lcm = n1 * n2 / gcd
    println("The LCM of $n1 and $n2 is $lcm.")
}

The output of this program is same as Example 1.

Here, inside the while loop, we calculate the GCD of the two numbers - n1 and n2. After the calculation, we use the above formula to calculate the LCM.

Did you find this article helpful?