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.