R Program to find the L.C.M


October 28, 2021, Learn eTutorial
870

How to find the LCM of given numbers

LCM or Least Common Multiple is the smallest positive integer that is perfectly divisible by two given numbers. For example, the LCM of 6 and 8 is 24.  The L.C.M. should be greater than or equal to the largest number among two given numbers. 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. 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.

How LCM check is implemented in R Program

We are using readline() function for taking the user's input. In this R program, we accept the user's values into n1, and n2 by providing an appropriate message to the user using 'prompt'. First, find the largest number among n1 and n2. Now using an infinite while loop, check if both the input numbers perfectly divide our number. And store the number as L.C.M

ALGORITHM

STEP 1: Prompting appropriate messages to the user

STEP 2: Take user input using readline() into variables n1, n2

STEP 3: First determine the largest of given numbers

STEP 4: Use an infinite while loop to go from that number and beyond

STEP 5: Check if both the input numbers perfectly divide our number

STEP 6: If yes store the number as L.C.M. and exit from the loop

STEP 7: else the number is incremented by 1 and the loop continues

 

R Source Code

                                          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: "))
print(paste("The L.C.M. of", n1,"and", n2,"is", lcm(n1, n2)))
                                      

OUTPUT

Enter first number: 3
Enter second number: 5
[1] "The L.C.M. of 3 and 5 is 15"