我是 R 编程语言的新手,想为这种简单的问题感到抱歉,并且已经处理了 R 中的 collatz 猜想的代码。实际上,我已经完全理解了前两部分,但我不了解 while 循环的逻辑在第 3 部分中,n.total <- NULL 的需要是什么。另外,我不明白为什么它在最后一步将整个集合作为一个向量与 c(n.total,n) 组合在一起。非常感谢您的帮助!
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