I have written a function that returns a prime factorization of numbers n less than 20. The function uses a let to create a list of exponents, and increments those exponents when it finds that n is divisible by a prime.
In my Lisp interpreter (both gcl and clisp), when I call the following function once, I get the correct factorization but when I call it a second time, I get the sum of the factorizations of the first and second function - but isn't the scope of exponents
limited to the inside of the let!? Why isn't exponents
being re-assigned the value '(0 0 0 0 0 0 0 0)
? How can I re-write this function so that it will withstand multiple calls?
(setf primes '(2 3 5 7 11 13 17 19))
(defun factorize (n)
(let ((exponents '(0 0 0 0 0 0 0 0)))
(loop for i from 0 to (- (length primes) 1) do
(loop while (and (= (mod n (nth i primes)) 0)
(not (= n 1))) do
(incf (nth i exponents))
(setf n (/ n (nth i primes)))))
(return-from factorize exponents)))
Output:
>(factorize 10) ;; first time
(1 0 1 0 0 0 0 0) ;; 2^1*5*1 = 10, correct
>(factorize 10)
(2 0 2 0 0 0 0 0) ;; wrong
>(factorize 10)
(3 0 3 0 0 0 0 0)