My Lisp solution, seems not so well, I will post others' solution below. I want to use the method learn from the SICP, but...something wrong happened. So I make some modification...
(defun DivBy3or5p(num)
(if (or (= 0 (rem num 3)) (= 0 (rem num 5)))
T
NIL))
(defun accumulate(initial seq)
(if (null seq)
initial
(+ (car seq)
(accumulate initial (cdr seq)))))
(defun enumerate-interval(low high)
(if (> low high)
nil
(cons low (enumerate-interval (+ low 1) high))))
(defun filterEulerOne(seq)
(if (null seq)
nil
(if (DivBy3or5p (car seq))
(cons (car seq) (filterEulerOne (cdr seq)))
(filterEulerOne (cdr seq)))))
(defun EulerProjectOne(n)
(accumulate 0
(filterEulerOne (enumerate-interval 0 n))))
Others' solution
Solution One
(let ((a (loop for i from 3 to 999 by 3 collect i))
(b (loop for i from 5 to 999 by 5 collect i)))
(apply #'+ (remove-duplicates (append a b))))
Solution Two
(defun problem-1 ()
(loop for x from 3 to 999
when (or
(zerop (mod x 3))
(zerop (mod x 5))) sum x))
Solution Three
(defun make-addr (step maximum)
(let ((i 0))
#'(lambda ()
(incf i step)
(cond ((>= i maximum) nil)
(t i)))))
(defun list-addr (addr)
(do ((x (funcall addr) (funcall addr))
(list '() (append list (list x))))
((null x) list)))
(apply #'+ (union (list-addr (make-addr 3 1000))
(list-addr (make-addr 5 1000))))
Solution Four
(defun zahlen (n)
(let ((summe 0))
(loop for i from 1 to n do
(when (or (= (mod i 3) 0)
(= (mod i 5) 0))
(incf summe i)))
summe))
Thursday, August 13, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment