【发布时间】:2019-03-09 04:25:50
【问题描述】:
我仍然主要为我自己(和我的学生)教授一些 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)
}
【问题讨论】:
-
google R collatz efficient- 前 2 次点击 - 应该有帮助 :) 不知道 R -
不幸的是,并非如此。我以前看过这些链接。他们甚至没有尝试明确地构造猜想中的数字序列。他们只是更新一个计数器来获取序列的长度。他们运行参数向量。尽管如此,非常有趣。谢谢...