How to resolve the algorithm Loops/Increment loop index within loop body step by step in the Common Lisp programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Loops/Increment loop index within loop body step by step in the Common Lisp programming language
Table of Contents
Problem Statement
Sometimes, one may need (or want) a loop which its iterator (the index variable) is modified within the loop body in addition to the normal incrementation by the (do) loop structure index.
Demonstrate the best way to accomplish this.
Write a loop which:
Extra credit: because of the primes get rather large, use commas within the displayed primes to ease comprehension.
Show all output here.
Not all programming languages allow the modification of a loop's index. If that is the case, then use whatever method that is appropriate or idiomatic for that language. Please add a note if the loop's index isn't modifiable.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Loops/Increment loop index within loop body step by step in the Common Lisp programming language
Source code in the common programming language
(defun primep (n) ; https://stackoverflow.com/questions/15817350/
(cond ((= 2 n) t) ; Hard-code "2 is a prime"
((= 3 n) t) ; Hard-code "3 is a prime"
((evenp n) nil) ; If we're looking at an even now, it's not a prime
(t ; If it is divisible by an odd number below its square root, it's not prime
(do* ((i 3 (incf i 2))) ; Initialize to 3 and increment by 2 on every loop
((or (> i (isqrt n)) ; Break condition index exceeds its square root
(zerop (mod n i))) ; Break condition it is divisible
(not (zerop (mod n i)))))))) ; Returns not divisible, aka prime
(do ((i 42) ; Initialize index to 42
(c 0)) ; Initialize count of primes to 0
((= c 42)) ; Break condition when there are 42 primes
(incf i) ; Increments index by unity
(if (primep i)(progn (incf c) ; If prime increment count of primes
(format t "~&~5<~d~;->~>~20<~:d~>" c i) ; Display count of primes found and the prime
(incf i (decf i))))) ; Increment index to previous index plus the prime
You may also check:How to resolve the algorithm URL parser step by step in the Lua programming language
You may also check:How to resolve the algorithm Validate International Securities Identification Number step by step in the Elixir programming language
You may also check:How to resolve the algorithm Price fraction step by step in the Elixir programming language
You may also check:How to resolve the algorithm Luhn test of credit card numbers step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the Pointless programming language