R Program to Find GCD of Two Numbers

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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) { return(a) } 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) 

Output:

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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare