# Write a R Program to Find GCD

Write a R Program to Find GCD

GCD Definition: The Greatest Common Divisor (GCD) of two integers is the largest positive integer that divides both numbers without leaving a remainder. It is often denoted as GCD(a,b) for two integers a and b.

Euclidean Algorithm: One of the commonly used algorithms to find the GCD of two numbers is the Euclidean Algorithm. It involves repeated application of the formula: GCD(a,b)=GCD(b,a modb)

The algorithm continues until the remainder becomes zero. The last non-zero remainder is the GCD of the two numbers.

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.

to Find GCD:

```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"

```

Conclusion:

In conclusion, the Greatest Common Divisor (GCD) is a fundamental concept in number theory, and it represents the largest positive integer that divides two given numbers without leaving a remainder. The Euclidean Algorithm is a widely used method to find the GCD efficiently. The provided R program takes two integers as input from the user, calculates their GCD using the Euclidean Algorithm, and then displays the result. It also includes a check for negative input, as the GCD is undefined for negative numbers. Understanding and computing the GCD are crucial in various mathematical and algorithmic applications.

Scroll to Top