Can someone point out my mistake here. I am trying to check if a number is a prime number or not. It works to an extent but I have a semantics error. For example it is telling me that 9 is a prime number but at the same time it is telling me 4 and 6 are not prime numbers and I am confused.
(defvar *prime* nil)
(defun primeCheck (x y)
(if (and (>= x y) (not (= (mod x y) 0)))
(progn
(setf y (+ y 1))
(primeCheck x y)
(setf *prime* 'yes))
(setf *prime* 'no))
)
(primeCheck 9 2)
(if (equal *prime* 'yes) (print "Number is prime") (print "Number is not prime"))
Many things are wrong.
How about using primarity test e.g. from SICP (structure and interpretation of computer programs)?
;; from SICP (here in clojure)
;; http://www.sicpdistilled.com/section/1.2.6/
(defun smallest-divisor (n)
(find-divisor n 2))
(defun square (n)
(* n n))
(defun find-divisor (n test-divisor)
(cond ((> (square test-divisor) n) n)
((dividesp test-divisor n) test-divisor)
(t (find-divisor n (1+ test-divisor)))))
(defun dividesp (a b)
(zerop (mod b a)))
(defun primep (n)
(= n (smallest-divisor n)))
primep
tests for primarity.