You are here: Home Blog Comments Re:キミならどう書く 2.0 - ROUND 1 -

Personal tools

Re:キミならどう書く 2.0 - ROUND 1 -

Posted by NANRI at 2006-06-21 23:45

lispの解が少ないので、Common Lispで。
xyzzyでも動作します。
(defun loop-generate-primes (n)
"ループ版"
(let ((prime '()))
(push 2 prime)
(do ((x 3 (+ x 2)))
((> x n))
(if (dolist (i prime t) (if (zerop (rem x i)) (return nil)))
(push x prime)))
(nreverse prime)))

(defun recursive-generate-primes (limit)
"再帰版"
(labels ((check (x prime)
(cond ((endp prime)
t)
((zerop (rem x (car prime)))
nil)
(t
(check x (cdr prime)))))
(main (n x prime)
(cond ((> x n)
(nreverse prime))
((check x prime)
(main n (+ x 2) (cons x prime)))
(t
(main n (+ x 2) prime)))))
(main limit 3 (list 2))))

Parent entry キミならどう書く 2.0 - ROUND 1 -