Why does this R code return 1 1 0? I understand why there is a zero at the end because 6 divided by 2 gives a remainder of 0. But I'm not sure how we got the 1 1. I thought that 6 divided by 2 is 3. I mean, okay, I guess Recall() means that the function will be repeated so we get 3 divided by 2 is 1. But anyway, I don't understand why there are two 1s. Could someone please explain? Thanks.
binary <- function(x) {
if(x == 0)
numeric()
else
c(Recall(x %/% 2), x %% 2)
}
binary(6)
CodePudding user response:
We can run the same function, but with some cat
statements so the recursive function can explain what it's doing, and in what order. Note that apart from the cat
calls, the function is exactly the same.
binary <- function(x) {
# Statement 1
cat("Function was given the value", x, "\n")
if(x == 0){
# Statement 2
cat(" - Value of 0 passed, therefore stopping.\n\n")
numeric()
}
else
{
# Statement 3
cat(" - inserting the remainder (", x%%2, ") to the result\n")
c(Recall(x %/% 2), x %% 2)
}
}
So now we can see:
binary(6)
#> Function was given the value 6
#> - inserting the remainder ( 0 ) to the result
#> Function was given the value 3
#> - inserting the remainder ( 1 ) to the result
#> Function was given the value 1
#> - inserting the remainder ( 1 ) to the result
#> Function was given the value 0
#> - Value of 0 passed, therefore stopping.
#>
#>[1] 1 1 0