我仍在自学R语言并向我的学生教授。
以下是R语言中Collatz数列的实现:
f <- function(n)
{
# construct the entire Collatz path starting from n
if (n==1) return(1)
if (n %% 2 == 0) return(c(n, f(n/2)))
return(c(n, f(3*n + 1)))
}
调用f(13)会得到以下结果:13、40、20、10、5、16、8、4、2和1。
但请注意,这里动态增加了一个向量的大小。这种操作通常会导致代码效率低下。是否有更高效的版本?
在Python中,我会使用:
def collatz(n):
assert isinstance(n, int)
assert n >= 1
def __colla(n):
while n > 1:
yield n
if n % 2 == 0:
n = int(n / 2)
else:
n = int(3 * n + 1)
yield 1
return list([x for x in __colla(n)])
我找到了一种不需要预先指定向量维度的写入方法。因此,一种解决方法可能是:
collatz <-function(n)
{
stopifnot(n >= 1)
# define a vector without specifying the length
x = c()
i = 1
while (n > 1)
{
x[i] = n
i = i + 1
n = ifelse(n %% 2, 3*n + 1, n/2)
}
x[i] = 1
# now "cut" the vector
dim(x) = c(i)
return(x)
}