Here we are explaining how to write an R program to find the HCF 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 HCF. The HCF is the largest positive integer that perfectly divides 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 HCF 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’. Here we first determine the smallest of the two given numbers. H.C.F should be less than or equal to the smallest number.
hcf <- function(x, y) {
# choose the smaller number
if(x > y) {
smaller = y
} else {
smaller = x
}
for(i in 1:smaller) {
if((x %% i == 0) && (y %% i == 0)) {
hcf = i
}
}
return(hcf)
}
# take input from the user
# n1 = as.integer(readline(prompt = "Enter first number: "))
# n2 = as.integer(readline(prompt = "Enter second number: "))
# take input as integer
n1 = as.integer(48)
n2 = as.integer(31)
print(paste("The H.C.F. of", n1,"and", n2,"is", hcf(n1, n2)))
## [1] "The H.C.F. of 48 and 31 is 1"
# take input from the user
# n1 = as.integer(readline(prompt = "Enter first number: "))
# n2 = as.integer(readline(prompt = "Enter second number: "))
# take input as integer
n1 = as.integer(12)
n2 = as.integer(18)
print(paste("The H.C.F. of", n1,"and", n2,"is", hcf(n1, n2)))
## [1] "The H.C.F. of 12 and 18 is 6"