理解 R 中的 Collatz 函数代码

问题描述 投票:0回答:1

我是 R 编程语言的新手,对这种简单的问题感到抱歉,并处理了 R 中的 collatz 猜想的代码。实际上,我已经完全理解了前两部分,但我不明白 while 的逻辑第 3 部分中的循环以及 n.total 需要什么 <- NULL. In addition, I dont understand the reason why it is combining the whole set as a vector in the last step with c(n.total,n). Thank you very much for your 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

编辑

必须给予学分。
上面的代码来自这个R-bloggers代码

r function math functional-programming collatz
1个回答
3
投票
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) 将返回:5 16 8 4 2 1

© www.soinside.com 2019 - 2024. All rights reserved.