Understanding this Collatz function code in R -
i new r programming language , want sorry kind of easy question , have dealed code of collatz conjecture in r. actually, have understood first 2 parts, dont logic of while loop in part 3 , need of n.total <- null. in addition, dont understand reason why combining whole set vector in last step c(n.total,n). thank help!
part 1: is.even <- function(x){ if(x%%2==0){ print("true") }else{ print("false") } } part 2: collatz <- function(n){ if (is.even(n)) { n/2 }else{ 3*n+1 } } part 3: n <- 27 n.total <- null while(n != 1){ n <- collatz(n) n.total <- c(n.total,n) } n.total
collatz <- function(n, acc=c()) { if(n==1) return(c(acc, 1)); collatz(ifelse(n%%2==0, n/2, 3*n +1), c(acc, n))} collatz(5) return: 5 16 8 4 2 1
Comments
Post a Comment