Learn how to find the Least Common Multiple (LCM) using R programming language. Explore an efficient approach for calculating LCM in R.
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.
Program:
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: 48
[1] "The L.C.M. of 24 and 48 is 48"