145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
My Solution
(defun factorial(n)
(factorial-iter n 1))
(defun factorial-iter(n result)
(if (> n 0)
(factorial-iter (- n 1) (* n result))
result))
(defun factorialsum(n)
(let ((numberstr (format nil "~a" n)))
(loop for i from 0 to (- (length numberstr) 1)
sum (factorial (parse-integer numberstr :start i :end (+ i 1))))))
(defun Euler34-iter(n)
(loop for i from 3 to n
collect (if (= i (factorialsum i))
i)))
(defun Euler34(n)
(remove-if #'(lambda(x)(null x)) (Euler34-iter n)))
First Solution
(defun digits (num)
(map 'list
#'(lambda (char) (read-from-string (string char)))
(prin1-to-string num)))
#'(lambda (char) (read-from-string (string char)))
(prin1-to-string num)))
(defun digit-fact (n)
(aref #(1 1 2 6 24 120 720 5040 40320 362880 3628800) n))
(defun fact-sum (num)
(apply #'+ (mapcar #'digit-fact (digits num))))
(defun euler34 ()
(loop for n from 10 to (* 6 (digit-fact 9))
when (= n (fact-sum n))
collect n))
collect n))
(defconstant vec #(1 1 2 6 24 120 720 5040 40320 362880))
(defun euler34 ()
(let ((total 0))
(do ((i 3 (+ i 1)))
((> i (upper-bound 2)) total)
((> i (upper-bound 2)) total)
(if (= i (sum-factorials-digits (format nil "~A" i)))
(incf total i)))))
(incf total i)))))
(defun upper-bound (n)
(if (> (expt 10 n) (* n (svref vec 9)))
(* n (svref vec 9))
(upper-bound (+ n 1))))
(* n (svref vec 9))
(upper-bound (+ n 1))))
(defun sum-factorials-digits (str)
(if (zerop (length str))
0
(+ (svref vec (- (char-code (elt str 0)) 48))
(sum-factorials-digits (subseq str 1))))))
0
(+ (svref vec (- (char-code (elt str 0)) 48))
(sum-factorials-digits (subseq str 1))))))
Third Solution
(defun problem-34 ()
(loop for x from 1 to 999999
when (= x (reduce #'+ (mapcar #'fact-tr (digits x)))) sum x))
(defun fact-tr (n &optional (acc 1))
(if (<= n 1)
acc
(fact-tr (- n 1) (* acc n))))
acc
(fact-tr (- n 1) (* acc n))))
(defun digits (num)
(map 'list #'(lambda (char) (read-from-string (string char))) (prin1-to-string num)))
No comments:
Post a Comment