Answer the question
In order to leave comments, you need to log in
How to write fast exponentiation?
I'm trying to write tail recursion fast exponentiation:
(defun fastexpt-iter (n p count)
(format t "n: ~A p: ~A count: ~A ~%" n p count)
(if (= 1 p)
count
(if (evenp p)
(fastexpt-iter n (/ p 2) (* count count))
(fastexpt-iter n (1- p) (* n count)))))
(defun fastexpt (n p)
(if (zerop p)
1
(if (evenp p)
(fastexpt-iter n p n)
(fastexpt-iter n p 1))))
Answer the question
In order to leave comments, you need to log in
Does not work.
(defun fastexpt-iter (n p a)
(format t "n: ~A p: ~A a: ~A~%" n p a)
(if (= 1 p)
(* n a)
(if (evenp p)
(fastexpt-iter (* n n) (/ p 2) a)
(fastexpt-iter n (1- p) (* a n)))))
(defun fastexpt (n p)
(if (zerop p)
1
(fastexpt-iter n p 1)))
What am I doing wrong?
fastexpt-iter(n, p, a) = n ^ p * a
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question