I'm defining a function to test if a number is prime and I have an algorithm which works (in Python) and I have ported most of it to Lisp. The problem however is that my primality test keeps passing even when it shouldn't. For example, isPrime(13)
still reaches the return NIL
even though it should fail the when
condition.
(defun isPrime(n)
(cond
((< n 2); numbers less than 2 aren't prime
NIL
)
((equal n 2); 2 is the only even prime
T
)
((equal (rem n 2) 0); Even numbers are never prime (besides 2)
NIL
)
((> n 2)
(loop for i from 2 to n do(
when(equal (rem n i) 0);If n is evenly divisible by i, we have found a factor other than 1 and n
(return NIL)
)
)
)
(t T); If we get through all that with no issue, the number is prime
)
)
Question: Why does my function reach the return NIL
branch no matter what?
Also, if this is just a bad approach to testing primality, is there a more lisp-like way of doing this (not worried about performance, just algorithmic correctness and readability.)