LISP: Computing Prime Numbers Between 1 and 25 (Inclusive)
To “write a function in LISP that computes prime number between 1 and 25 (inclusive)”, the most reliable approach is to (1) define a predicate prime? and then (2) build a function that enumerates candidates and filters using that predicate. A standard number-theory optimization is to check divisibility only up to , because any composite has a factor .
A minimal Common Lisp solution typically uses integer loops and modular arithmetic: mod and dolist or loop.
Below is a complete, idiomatic Common Lisp implementation that returns the list of primes in the interval (i.e., ).
Keyword map: prime?, mod, sqrt, loop.
Common Lisp: Functions, loops, and basics (learning to read the code)
Prime predicate design
A number is prime if:
- is not prime,
- otherwise, test whether any integer in divides evenly (i.e., ).
This uses the divisor bound , reducing work while remaining correct.
Warning: if you accidentally start testing from , then every will appear “divisible” by and you’ll misclassify primes. Always begin at .
prime? and divisor are the core logic pieces.
Build the two functions: prime? then primes-between
- 1Step 1
Return NIL for , return T for ; even numbers greater than 2 are not prime using evenp.
- 2Step 2
Let using isqrt so the loop stays integer-only.
- 3Step 3
Loop from 3 to limit by 2 and check mod with (zerop (mod n d)). If any divisor works, return NIL; otherwise return T.
- 4Step 4
Use a loop from 1 to 25 and collect n whenever (prime? n) is true.
Pro Tip: prefer list-returning functions
If your goal is “compute primes between 1 and 25”, returning a list is the most useful shape. In Common Lisp, loop with collect makes this natural.
Common bug: wrong loop condition for divisibility
If you accidentally write something like for d below limit (excluding the limit) you can misclassify squares (e.g., or ) because the actual factor can equal . Use an inclusive upper bound when checking .
How you should develop this solution
Define prime? predicate
Step 1Implement edge cases, even check, then divisor test up to ."
Enumerate interval
Step 2Loop over from 1 to 25 inclusive and filter using (prime? n)."
Verify with known primes
Step 3Expected output: (2 3 5 7 11 13 17 19 23)."
Common variants and edge cases
Primes between 1 and 25
Expected result list values
Knowledge Check
In a prime-checking function, why do we test divisors only up to ?