How to resolve the algorithm Count in factors step by step in the Common Lisp programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Count in factors step by step in the Common Lisp programming language

Table of Contents

Problem Statement

Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself.

2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as

2 × 3

{\displaystyle 2\times 3}

. 2144   is not prime;   it would be shown as

2 × 2 × 2 × 2 × 2 × 67

{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}

.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Count in factors step by step in the Common Lisp programming language

Source code in the common programming language

(defparameter *primes*
  (make-array 10 :adjustable t :fill-pointer 0 :element-type 'integer))

(mapc #'(lambda (x) (vector-push x *primes*)) '(2 3 5 7))

(defun extend-primes (n)
  (let ((p (+ 2 (elt *primes* (1- (length *primes*))))))
    (loop for i = p then (+ 2 i)
	  while (<= (* i i) n) do
	  (if (primep i t) (vector-push-extend i *primes*)))))

(defun primep (n &optional skip)
  (if (not skip) (extend-primes n))
  (if (= n 1) nil
      (loop for p across *primes* while (<= (* p p) n)
	    never (zerop (mod n p)))))

(defun factors (n)
  (extend-primes n)
  (loop with res for x across *primes* while (> n (* x x)) do
	(loop while (zerop (rem n x)) do
	      (setf n (/ n x))
	      (push x res))
	finally (return (if (> n 1) (cons n res) res))))

(loop for n from 1 do
      (format t "~a: ~{~a~^ × ~}~%" n (reverse (factors n))))


(defun factors (n)
  (loop with res for x from 2 to (isqrt n) do
	(loop while (zerop (rem n x)) do
	      (setf n (/ n x))
	      (push x res))
	finally (return (if (> n 1) (cons n res) res))))

(loop for n from 1 do
      (format t "~a: ~{~a~^ × ~}~%" n (reverse (factors n))))


  

You may also check:How to resolve the algorithm Maze generation step by step in the XPL0 programming language
You may also check:How to resolve the algorithm String length step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Idiomatically determine all the lowercase and uppercase letters step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Knuth shuffle step by step in the Julia programming language
You may also check:How to resolve the algorithm Reverse a string step by step in the COBOL programming language