Here we are explaining how to write an R program to find the LCM of the given two numbers. We can use the readline() function to take input from the user (terminal). Here the prompt argument can choose to display an appropriate message for the user. The program first asks for two integers and passes them to a function and returns the L.C.M. The L.C.M. should be greater than or equal to the largest number among two given numbers.LCM is the smallest positive integer that is perfectly divisible by the two given numbers.
We are using readline() function for taking the user’s input. Given below are the steps which are used in the R program to find the LCM of two numbers. In this R program, we accept the user’s values into n1,n2 by providing an appropriate message to the user using ‘prompt’. First, find the largest number among n1 and n2.In while loop checks if both the input numbers perfectly divide our number. And store the number as L.C.M
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
#n1 = as.integer(readline(prompt = "Enter first number: "))
#n2 = as.integer(readline(prompt = "Enter second number: "))
# assign numbers to the variables: n1 and n2
n1 = 32
n2 = 27
print(paste("The L.C.M. of", n1,"and", n2,"is", lcm(n1, n2)))
## [1] "The L.C.M. of 32 and 27 is 864"
# assign numbers to the variables: n1 and n2
n1 = 12
n2 = 21
print(paste("The L.C.M. of", n1,"and", n2,"is", lcm(n1, n2)))
## [1] "The L.C.M. of 12 and 21 is 84"