Kotlin Program to Find LCM With Example

In this post, we will go through kotlin program to find LCM of two numbers.

What is LCM?

LCM (Least Common Multiple) of two numbers is smallest number that is divisible by both.

For Example,

LCM of 30 and 20 is 60
Explanation:

60 / 20 = 3
60 / 30 = 2

We can find LCM using below ways –

  1. Simple Way
  2. Using Prime Factors
  3. Using GCD

In this post, we learn to find Least Common Multiple (LCM) of two number using simple method.

1. Program to Find LCM of Two Numbers (Simple Way)

We use simple while loop and if-else block to find least common factor of two numbers.

Sourcecode –

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter a:")
    val a = read.nextInt()

    println("Enter b:")
    val b = read.nextInt()

    val lcm = findLCM(a, b)

    println("LCM of $a and $b: $lcm")
}

private fun findLCM(a: Int, b: Int): Int {

    val biggerNum = if(a > b) a else b
    var lcm = biggerNum
    while(true) {

        // Break loop we get number divisible by a and b both.
        if(((lcm % a) == 0) && ((lcm % b) == 0)) {
            break
        }

        lcm  += biggerNum
    }

    return lcm
}

When you run the program, output will be

Enter a:
13
Enter b:
17
LCM of 13 and 17: 221

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.
Input read by scanner is then stored in variable number

Let Assume a = 20, b = 30

So, findLCM(20, 30) function is called.
At first,
Variable lcm = 30 because 30 > 20.

A while loop is run.
Note: while loop is exited only when lcm is divisible by both numbers.

At first, lcm = 30
Since lcm is not divisible by 20. ((lcm % a) == 0) && ((lcm % b) == 0) condition fails.
Value of lcm is incremented by 30 (30 > 20).

Now, lcm = 60.
lcm is divisible by 20 and 30 both. ((lcm % a) == 0) && ((lcm % b) == 0) condition succeeds.
So, while loop breaks.

Finally, 60 is returned.

We went through Kotlin program to find LCM of two numbers.

Leave a Reply