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:
56and98 - Output:
GCD: 14
Solution Steps
- Read the Two Numbers: Use the
readline()function to take the two numbers as input from the user. - Convert the Inputs to Numeric: Convert the inputs from character strings to numeric values using the
as.numeric()function. - Define a Function to Calculate GCD: Implement the Euclidean algorithm to find the GCD.
- Call the GCD Function: Use the function to calculate the GCD of the two numbers.
- 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 usingas.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 theresultvariable.
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.