Find GCD with Recursion in R
R Programming: Control Structure Exercise-11 with Solution
Write a R program function to find the GCD (Greatest Common Divisor) of two numbers using recursion.
Sample Solution :
R Programming Code :
# Define a function to find the GCD of two numbers using recursion
gcd <- function(a, b) {
# Base case: If b is 0, GCD is a
if (b == 0) {
return(a)
} else {
# Recursive case: Find GCD using Euclidean algorithm
return(gcd(b, a %% b))
}
}
# Test the function with example inputs
num1 <- 44
num2 <- 16
result <- gcd(num1, num2)
# Print the result
cat("The GCD of", num1, "and", num2, "is:", result, "\n")
Output:
The GCD of 44 and 16 is: 4
Explatnaion:
In the exercise above,
- The "gcd()" function takes two parameters 'a' and 'b', representing the two numbers for which the GCD is to be found.
- It starts with a base case: if 'b' is 0, the GCD is 'a'.
- If 'b' is not 0, it uses recursion to find the GCD using the Euclidean algorithm, which states that the GCD of two numbers 'a' and 'b' is the same as the GCD of 'b' and the remainder when 'a' is divided by 'b'.
- The function is then tested with example inputs ('num1' and 'num2'), and the result is printed to the console.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Check Armstrong number with While loop in R.
Next: Generate Pascal's Triangle with For loops in R.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/r-programming-exercises/control-structure/r-programming-control-structure-exercise-11.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics