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

Published on 12 May 2024 09:40 PM

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

Table of Contents

Problem Statement

A factorion is a natural number that equals the sum of the factorials of its digits.

145   is a factorion in base 10 because:

It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999.

Write a program in your language to demonstrate, by calculating and printing out the factorions, that:

Let's start with the solution:

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

Source code in the common programming language

(defparameter *bases* '(9 10 11 12))
(defparameter *limit* 1500000)

(defun ! (n) (apply #'* (loop for i from 2 to n collect i)))

(defparameter *digit-factorials* (mapcar #'! (loop for i from 0 to (1- (apply #'max *bases*)) collect i)))

(defun fact (n) (nth n *digit-factorials*))

(defun digit-value (digit)
  (let ((decimal (digit-char-p digit)))
    (cond ((not (null decimal)) decimal)
          ((char>= #\Z digit #\A) (+ (char-code digit) (- (char-code #\A)) 10))
          ((char>= #\z digit #\a) (+ (char-code digit) (- (char-code #\a)) 10))
          (t nil))))

(defun factorionp (n &optional (base 10))
  (= n (apply #'+
            (mapcar #'fact
                    (map 'list #'digit-value
                         (write-to-string n :base base))))))

(loop for base in *bases* do
  (let ((factorions
        (loop for i from 1 while (< i *limit*) if (factorionp i base) collect i)))
    (format t "In base ~a there are ~a factorions:~%" base (list-length factorions))
    (loop for n in factorions do
      (format t "~c~a" #\Tab (write-to-string n :base base))
      (if (/= base 10) (format t " (decimal ~a)" n))
      (format t "~%"))
    (format t "~%")))


  

You may also check:How to resolve the algorithm Compare length of two strings step by step in the Delphi programming language
You may also check:How to resolve the algorithm Bitmap/Write a PPM file step by step in the Rust programming language
You may also check:How to resolve the algorithm Four bit adder step by step in the F# programming language
You may also check:How to resolve the algorithm A+B step by step in the Golo programming language
You may also check:How to resolve the algorithm Variadic function step by step in the COBOL programming language