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

February 5, 2023, Learn eTutorial

How to find the HCF or GCD of given numbers

HCF is the short form of the Highest Common Factor, it is the largest number that can able to divide all the given numbers that we need to find the HCF. It is also called as GCD. Let us make it easy with an example, consider 2 numbers like 20 and 30, the HCF of 20 and 30 will be 10 because 10 is the largest number that can divide both 20 and 30 completely. 

How we find HCF or GCD using the R Program

In this R program, we accept the user's values into n1, n2 by providing an appropriate message to the user using 'prompt'. We are using readline() function for taking the user's input. Then we first determine the smallest of the two given numbers. H.C.F. should be less than or equal to the smallest number. Now we open a for loop from 1 and check the factors of these numbers which we need to find the HCF using mod operator. In each loop iteration, we are adding the factor to a variable and after the loop, we get the HCF in that variable.


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 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
# 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)))


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