Write a R Program to Find GCD

Write a R Program to Find GCD

The highest common factor (H.C.F) or greatest common divisor (G.C.D) of two numbers is the largest positive integer that perfectly divides the two given numbers.
For example, the H.C.F of 12 and 14 is 2.

Program:

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
num1 = as.integer(readline(prompt = “Enter first number: “))
num2 = as.integer(readline(prompt = “Enter second number: “))
print(paste(“The H.C.F. of”, num1,”and”, num2,”is”, hcf(num1, num2)))

Output:
Enter first number: 12
Enter second number: 24
[1] “The H.C.F. of 12 and 24 is 12”

No Comments

Post a Reply