R Program to find the L.C.M


February 5, 2023, Learn eTutorial
1927

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 2 and 3 is 6.  The L.C.M. should be greater than or equal to the largest number among two given numbers.

How LCM check is implemented in R Program

In this R program, We are using readline() function for taking the user's input. store that user's values into n1, and n2. Now, find the largest number among n1 and n2. Then using an infinite while loop, check if both the input numbers can perfectly divide our number (greater) in the loop. And store the number as L.C.M. else increment the greater until we find a number which our input numbers can divide and print that as LCM.

ALGORITHM

STEP 1: Ask the user to enter an input

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"