R Program to Find L.C.M.

In this example, you will learn to find the L.C.M of two numbers entered by the user by creating a user-defined function.

To understand this example, you should have the knowledge of the following R programming topics:


The least common multiple (L.C.M.) of two numbers is the smallest positive integer that is perfectly divisible by the two given numbers. For example, the L.C.M. of 12 and 14 is 84.


Example: Compute LCM in R

# Program to find the L.C.M. of two input number
lcm  y) {
        greater = x
    } else {
        greater = y
    }

    while(TRUE) {
        if((greater %% x == 0) && (greater %% y == 0)) {
            lcm = greater
            break
        }
        greater = greater + 1
    }
    return(lcm)
}

# take input from the user
num1 = as.integer(readline(prompt = "Enter first number: "))
num2 = as.integer(readline(prompt = "Enter second number: "))

print(paste("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2)))

Output

Enter first number: 24
Enter second number: 25
[1] "The L.C.M. of 24 and 25 is 600"

This program asks for two integers and passes them to a function which returns the L.C.M.

In the function, we first determine the greater of the two number since the L.C.M. can only be greater than or equal to the largest number.

We then use an infinite while loop to go from that number and beyond.

In each iteration, we check if both the input numbers perfectly divides our number. If so, we store the number as L.C.M. and break from the loop. Otherwise, the number is incremented by 1 and the loop continues.

The above program is slower to run. We can make it more efficient by using the fact that the product of two numbers is equal to the product of least common multiple and greatest common divisor of those two numbers.

Number1 * Number2 = L.C.M. * G.C.D.
Did you find this article helpful?