fastread homefastrread library fastread menu

R Programming : Find L.C.M.

Tutorial by:Maria Ghoste      Date: 2016-06-10 02:29:37

❰ Previous Next ❱

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.

Source Code

# Program to find the
# L.C.M. of two input number

lcm <- function(x, y) {
    # choose the greater number
    if(x > 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.

❰ Previous Next ❱


R Programming

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website