【发布时间】:2017-08-05 04:50:47
【问题描述】:
作为我的一门课的测试,我们的老师要求我们测试著名的欧几里得算法的递归和非递归方法:
迭代
(defun gcdi (a b)
(let ((x a) (y b) r)
(while (not (zerop y))
(setq r (mod x y) x y y r))
x))
递归
(defun gcdr (a b)
(if (zerop b)
a
(gcdr b (mod a b))))
然后我进行了测试:
(defun test-iterative ()
(setq start (float-time))
(loop for x from 1 to 100000
do (gcdi 14472334024676221 8944394323791464)) ; Fibonacci Numbers close to 2^64 >:)
(- (float-time) start))
(defun test-recursive ()
(setq start (float-time))
(loop for x from 1 to 100000
do (gcdr 14472334024676221 8944394323791464)) ; Fibonacci Numbers close to 2^64 >:)
(- (float-time) start))
然后我运行了计时器:
(test-recursive)
:1.359128475189209
(test-iterative)
:1.7059495449066162
所以我的问题是,为什么递归测试的执行速度比迭代测试快?迭代几乎总是比递归更好吗? elisp 是个例外吗?
【问题讨论】: