English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to find the least common multiple (LCM) of two numbers

Comprehensive Collection of Kotlin Examples

In this program, you will learn to useGreatest Common DivisorFind the least common multiple of two numbers. This is done through a while loop in Kotlin.

The least common multiple of two integers is the smallest positive integer that can be completely divided by both numbers (without a remainder).

Example1: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
    //n1and n2The maximum value between them is stored in lcm
    lcm = if (n1 > n2) n1 else n2
    // always true
    while (true) {
        if (lcm % n1 == 0 && lcm % n2 == 0) {
            println("$n1and $n2The LCM of $n is $lcm.")
            break
        }
        ++lcm
    }
}

When running the program, the output is:

72 and12The latest common multiple of 0 and 0 is360.

In this program, the two numbers to find the least common multiple are stored in the variables n1and n2。
Then, we first set lcm to the largest of the two numbers.
This is because, the least common multiple cannot be less than the largest number. In an infinite while loop (while(true)), we check if lcm is completely divisible by n1and n2。
If so, we have found the least common multiple. We print the least common multiple and use the break statement to exit the while loop.

This is the equivalent Java code:Java program to find the 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, please checkKotlin program to find the GCD of two numbers

Example2: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) {
        // Check if i is a factor of two integers
        if (n1 % i == 0 && n2 % i == 0)
            gcd = i
        ++i
    }
    val lcm = n1 * n2 / gcd
    println("$n1 and $n2 The least common multiple is $lcm.
}

The output of the program is as follows1are the same.

Here, in the while loop, we calculate two numbers-n1and n2After calculating the GCD, we use the above formula to calculate the LCM.

Comprehensive Collection of Kotlin Examples