So I'm trying to learn R and using a number of resources including a book called "Discovering Statistics using R" and a bunch of other cool eBooks.
I understand a great method in programming is the Euclid's Algorithm.
Implementing it in a loop can be achieved like this:
gcd(x,y) //assuming x is the largest value
//do
r = x%y;
x = y;
y = r;
//while r != 0;
return x;
After several searches on Google, SO and Youtube refreshing my memory of gcd algorithms, I wasn't able to find one that doesn't use a loop. Even recursive methods seem to use loops.
How can this be achieved in R without the use of loops or if statements?
Thanks in advance.
gcd(x,y) //assuming x is the largest value //do r = x%y; x = y; y = r; //while r !=
Example: Program to Find GCD In the function, we first determine the smaller of the two number since the H.C.F can only be less than or equal to the smallest number. We then use a for loop to go from 1 to that number. In each iteration we check if our number perfectly divides both the input numbers.
If a and b are two numbers then the greatest common divisor of both the numbers is denoted by gcd(a, b). To find the gcd of numbers, we need to list all the factors of the numbers and find the largest common factor. Therefore, we can conclude that 4 is the highest common factor among all three numbers.
Reducing GCD for two integers enables you to compute GCD for any sequence of integers (sorted or not):
gcd2 <- function(a, b) {
if (b == 0) a else Recall(b, a %% b)
}
gcd <- function(...) Reduce(gcd2, c(...))
Using the statement "without loops or the if
statement" literally, here is a recursive version that uses ifelse
:
gcd <- function(x,y) {
r <- x%%y;
return(ifelse(r, gcd(y, r), y))
}
One might not expect it, but this is actually vectorized:
gcd(c(1000, 10), c(15, 10))
[1] 5 10
A solution using if
would not handle vectors of length greater than 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With