Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
My Solution
(defun enumerate-interval (low high)
(loop for i from low to high
collect i))
(defun fifthpower(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)) 5))))
(defun Euler30()
(remove-if-not #'(lambda(x) (= x (fifthpower x))) (enumerate-interval 1 9999999)))
(apply #'+ (Euler30))
Others' Solution
First Solution
(defun digits (num)
(map 'list
#'(lambda (char) (read-from-string (string char)))
(prin1-to-string num)))
(defun digit-power (num power)
(reduce #'+ (map 'list #'(lambda (n) (expt n power)) (digits num))))
(defun sum-of-digit-powers (power)
(let ((limit (loop for i from 1
for j = (* i (expt 9 power))
when (< j (expt 10 i))
return j)))
(loop for i from 2 to limit
when (= i (digit-power i power))
sum i)))
(defun euler30 ()
(sum-of-digit-powers 5))
(map 'list
#'(lambda (char) (read-from-string (string char)))
(prin1-to-string num)))
(defun digit-power (num power)
(reduce #'+ (map 'list #'(lambda (n) (expt n power)) (digits num))))
(defun sum-of-digit-powers (power)
(let ((limit (loop for i from 1
for j = (* i (expt 9 power))
when (< j (expt 10 i))
return j)))
(loop for i from 2 to limit
when (= i (digit-power i power))
sum i)))
(defun euler30 ()
(sum-of-digit-powers 5))
Second Solution
(defun digit-sum (n fn)
(labels ((f-s (n res)
(if (zerop n)
res
(f-s (floor n 10) (+ res (funcall fn (mod n 10)))))))
(f-s n 0)))
(defun math-30 ()
"Find the sum of all numbers which are equal to the sum of 5th power of their digits"
(do ((i 2 (1+ i))
(result 0 (if (= i (digit-sum i #'(lambda (n) (expt n 5)))) (+ result i) result)))
((> i 360000) result)))
(labels ((f-s (n res)
(if (zerop n)
res
(f-s (floor n 10) (+ res (funcall fn (mod n 10)))))))
(f-s n 0)))
(defun math-30 ()
"Find the sum of all numbers which are equal to the sum of 5th power of their digits"
(do ((i 2 (1+ i))
(result 0 (if (= i (digit-sum i #'(lambda (n) (expt n 5)))) (+ result i) result)))
((> i 360000) result)))
No comments:
Post a Comment