Saturday, August 22, 2009

Euler Project 92

A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.

For example,

44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89

Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.

How many starting numbers below ten million will arrive at 89?


My Solution

(defun squartsum(n)
  (let ((numberstr (format nil "~a" n)))
    (loop for i from 0 to (- (length numberstr) 1)
            sum (expt (parse-integer numberstr :start i :end (+ i 1)) 2))))

(defun IsEnd89(n)
  (let ((currentstage (squartsum n)))
    (loop
      (if (= 89 currentstage)
          (return T)
         (if (= 1 currentstage)
             (return nil)
             (setq currentstage (squartsum currentstage)))))))

(defun Euler(n)
  (let ((numberof89 0))
    (loop for j from 1 to n
          do(if (IsEnd89 j)
                  (progn (print j) (incf numberof89))))
    numberof89))

No comments:

Post a Comment