August 19, 2024

P39 - A list of prime numbers

Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.

lisp

;;; Determines the primes between K and N
(defun primes-between (k n)
(if (or (< n 1) (< n k))
()
(remove-smaller k (primes-up-to n))
)
)

;;; Removes smaller than K from a LIST
(defun remove-smaller (k list)
(remove-if #'(lambda (x) (< x k)) list)
)

;;; Returns the list with the primes up to N
;;; in ascending order

(defun primes-up-to (n)
(primes-up-to-aux () 2 n)
)

;;; Auxiliary accumulator function for calculating
;;; the primes up to N.
;;; L is the partial list of primes already obtained
;;; We want to complement L with the primes between
;;; K and N (defun primes-up-to-aux (l k n) (cond ((> k n) l) ((any-divides l k) (primes-up-to-aux l (1+ k) n)) (t (primes-up-to-aux (append l (list k)) (1+ k) n)) ) ;;; Predicate. True when some integer from the list ;;; LIST divides K (defun any-divides (list k) (some #'(lambda (x) (= 0 (mod k x))) list) )
Be first to comment
Leave a reply