R Program to Find GCD of Two Numbers

1. Introduction

The Greatest Common Divisor (GCD), also known as the Highest Common Factor (HCF), of two numbers is the largest number that can perfectly divide both numbers without leaving a remainder. Finding the GCD is essential in problems related to number theory and cryptography.

2. Program Overview

In this article, we are going to create a simple R program to find the GCD of two numbers using the Euclidean algorithm.

3. Code Program

# Function to find GCD using Euclidean algorithm
findGCD <- function(a, b) {
  # If the second number is 0, return the first number
  if(b == 0) {
  } else {
    return(findGCD(b, a %% b))  # Recursion with reduced values

# Reading two numbers
num1 <- as.integer(readline(prompt = "Enter the first number: "))
num2 <- as.integer(readline(prompt = "Enter the second number: "))

# Finding GCD
result <- findGCD(num1, num2)

# Printing the result
cat("The GCD of", num1, "and", num2, "is:", result)


Enter the first number: 56
Enter the second number: 98
The GCD of 56 and 98 is: 14

4. Step By Step Explanation

The program first defines a function findGCD that implements the Euclidean algorithm to find the GCD of two numbers. 

It's a recursive function where the base case is when the second number becomes 0. 

In the recursive call, the numbers are reduced based on the Euclidean algorithm. 

After defining the function, the program prompts the user to input two numbers. 

These numbers are then passed to the findGCD function to find their GCD. 

Finally, the result is printed to the console.