我是R编程语言的新手并且想为这种简单的问题感到抱歉并且已经在R中解密了collatz猜想的代码。实际上,我已经完全理解了前两部分,但我没有逻辑第3部分中的while循环以及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
答案 0 :(得分:2)
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
答案 1 :(得分:1)
is.even()
should return its result, not print it, which is breaking things. You can just use a direct logical expression for is.even()
:
is.even <- function(x) { x%%2==0 }
But it's so short you can inline it, no need for a function call. Also, prefer ifelse
expressions to if...else
ladders of assignments/expressions.
collatz <- function(n) { ifelse(n%%2==0, n/2, 3*n +1 }