Saturday, August 22, 2009

Euler Project 95



The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number.



Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair.



Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers:



12496 → 14288 → 15472 → 14536 → 14264 (→ 12496 → ...)



Since this chain returns to its starting point, it is called an amicable chain.



Find the smallest member of the longest amicable chain with no element exceeding one million.





My Solution



(defun factorialsum(n)


  (let* ((sqrtofn (sqrt n)) 

         (numbersum (loop for i from 2 to (floor sqrtofn)

                             when (zerop (rem n i))

                                      sum (+ i (/ n i)))))

         (progn (if (integerp sqrtofn)

                        (setq numbersum (- numbersum sqrtofn)))


   (+ numbersum 1))))






(defun lenghtofchain(n)


  (let ((original n)


(current n)


(lenght 1)


(previous 0))


    (loop 


      (progn (setq current (factorialsum current))


    (if (> current 1000000)

        (return 0))


    (if (= current original)


        (progn (return lenght))

        (if (= current 1)

            (progn (return lenght))

            (if (= current previous)

                (return 0)

                (if (> lenght 1000)

                     (return 0)))))


    (setq previous current)


    (incf lenght)))))






(defun Euler95(n)


  (let ((currentnumber 1)

         (maxlenght 0)

         (chainnumber 0)

         (currentlenght 0))


    (loop for i from 2 to n

         do(progn (setq currentlenght (lenghtofchain i))

                       (if (> currentlenght maxlenght)

                            (progn (setq maxlenght currentlenght)

                            (setq chainnumber i)))))


    chainnumber))


No comments:

Post a Comment