This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Taking exponent of a number

3 posts · 841 views

I am trying to make a function to take the yth power of number n.
(defun xp (x y)
                   (loop while (> 1 y) do
                         (setf x (* x x))
                         (setf y (- y 1))) (print x))
That is what I have now. Everytime I run the, the only output is whatever I enter for x, twice. Ex.

(xp 2 3) should print 8. Instead it just prints
2
2

(xp 10 2) should print 100. Instead it just prints
10
10

(xp 100 100) should print a huge number. Instead it just prints
100
100

Why is this?

Re: Taking exponent of a number

First, usually you don't want to print out the return value of a function, since the REPL will print it anyway, which is why you get the output echoed.

Your end condition is wrong since it says "execute the loop while one is greater than y", which is never true for your examples, so the value is never touched and returned as it was. Even if you fix that, it will not be exponentiation, since you are multiplying the modified value of x by itself, not by original.

Avoid using SETF. LOOP already has a large number of iteration constructs, which allow expressing state mutation in a structured way (I prefer iterate, code walking issues notwithstanding). Often it is possible to avoid a DO clause altogether.
(defun xp (x y)
  (loop repeat y
        for xprime = x then (* xprime x)
        finally (return xprime)))