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

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.


Example: Program to Find GCD

# Program to find the
# H.C.F of two input number

# define a function
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: 72
Enter second number: 120
[1] "The H.C.F. of 72 and 120 is 24"

This program asks for two integers and passes them to a function which returns the H.C.F.

In the function, we first determine the smaller of the two number since the H.C.F can only be less than or equal to the smallest number.

We then use a for loop to go from 1 to that number.

In each iteration we check if our number perfectly divides both the input numbers.

If so, we store the number as H.C.F. At the completion of the loop we end up with the largest number that perfectly divides both the numbers.

The above method is easy to understand and implement but not efficient. A much more efficient method to find the H.C.F. is the Euclidean algorithm.


Euclidean algorithm to Find GCD

This algorithm is based on the fact that H.C.F. of two numbers divides their difference as well.

In this algorithm, we divide the greater by smaller and take the remainder. Now, divide the smaller by this remainder. Repeat until the remainder is 0.

For example, if we want to find the H.C.F. of 54 and 24, we divide 54 by 24. The remainder is 6.

Now, we divide 24 by 6 and the remainder is 0. Hence, 6 is the required H.C.F. We can do this in Python as follows.

Example 2: GCD Using Euclidean algorithm


hcf <- function(x, y) {
    while(y) {
        temp = y
        y = x %% y
        x = temp
    }
    return(x)
}

Here we loop until y becomes zero.

In each iteration we place the value of y in x and the remainder (x % y) in y, using a temporary variable.

When y becomes zero, we have H.C.F. in x.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges