 # R Program to find H.C.F. or G.C.D

October 20, 2021, Learn eTutorial
711

## How to find the HCF or GCD of given numbers

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.

## How HCF check is implemented in R Program

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.

## 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 smaller of the two numbers

STEP 4: use a `for` loop to go from 1 to that number.

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

STEP 6: `If` yes store the number as H.C.F. and exit from the loop

STEP 7: End of the loop, we get the largest number that perfectly divides both the numbers.

## R Source Code

```                                          ```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: "))
print(paste("The H.C.F. of", n1,"and", n2,"is", hcf(n1, n2)))```
```

## OUTPUT

```Enter first number: 150
Enter second number: 225
 "The H.C.F. of 150 and 225 is 75"```