Page 1 of 1

Taking exponent of a number

Posted: Thu Sep 02, 2010 10:16 pm
by SterlingM
I am trying to make a function to take the yth power of number n.

Code: Select all

(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

Posted: Thu Sep 02, 2010 11:05 pm
by ramarren
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.

Code: Select all

(defun xp (x y)
  (loop repeat y
        for xprime = x then (* xprime x)
        finally (return xprime)))

Re: Taking exponent of a number

Posted: Fri Sep 03, 2010 5:43 am
by Tom
Just to be clear, you are writing your own exponent function for practice, right? Otherwise, you should use EXPT.

Good luck,

~ Tom