我仍然主要向我自己(和我的学生)教授一些 R。
下面是 Collatz 序列在 R 中的实现:
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)
}