R Program to Find the GCD of Two Numbers

Introduction

The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them without leaving a remainder. This guide will walk you through writing an R program that finds the GCD of two numbers using the Euclidean algorithm.

Problem Statement

Create an R program that:

  • Prompts the user to enter two numbers.
  • Calculates the GCD of the two numbers.
  • Displays the GCD.

Example:

  • Input: 56 and 98
  • Output: GCD: 14

Solution Steps

  1. Read the Two Numbers: Use the readline() function to take the two numbers as input from the user.
  2. Convert the Inputs to Numeric: Convert the inputs from character strings to numeric values using the as.numeric() function.
  3. Define a Function to Calculate GCD: Implement the Euclidean algorithm to find the GCD.
  4. Call the GCD Function: Use the function to calculate the GCD of the two numbers.
  5. Display the GCD: Use the print() function to display the result.

R Program

# R Program to Find the GCD of Two Numbers
# Author: https://www.javaguides.net/

# Step 1: Read the first number from the user
num1 <- as.numeric(readline(prompt = "Enter the first number: "))

# Step 2: Read the second number from the user
num2 <- as.numeric(readline(prompt = "Enter the second number: "))

# Step 3: Function to calculate GCD using Euclidean algorithm
gcd <- function(a, b) {
  while (b != 0) {
    temp <- b
    b <- a %% b
    a <- temp
  }
  return(a)
}

# Step 4: Calculate the GCD of the two numbers
result <- gcd(num1, num2)

# Step 5: Display the GCD
print(paste("GCD:", result))

Explanation

Step 1: Read the First Number

  • The readline() function prompts the user to enter the first number. The input is read as a string, so it is converted to a numeric value using as.numeric().

Step 2: Read the Second Number

  • Similarly, the readline() function is used to prompt the user for the second number, which is also converted to a numeric value.

Step 3: Define the GCD Function

  • The gcd() function implements the Euclidean algorithm. It repeatedly replaces the larger number with its remainder when divided by the smaller number until the remainder is zero. The last non-zero remainder is the GCD.

Step 4: Calculate the GCD

  • The program calls the gcd() function with the two input numbers and stores the result in the result variable.

Step 5: Display the GCD

  • The print() function is used to display the calculated GCD.

Output Example

Example:

Enter the first number: 56
Enter the second number: 98
[1] "GCD: 14"

Conclusion

This R program demonstrates how to calculate the GCD of two numbers using the Euclidean algorithm. It covers important programming concepts such as loops, functions, and user input, making it a practical example for beginners learning R programming.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top