Skip to content

Instantly share code, notes, and snippets.

@hidsh
Created October 20, 2012 14:49
Show Gist options
  • Save hidsh/3923475 to your computer and use it in GitHub Desktop.
Save hidsh/3923475 to your computer and use it in GitHub Desktop.
elisp: Sieve of Eratosthenes
(defun iota (max &optional min)
"minからmaxまでの整数をリストで返す。min省略時は1から。"
(unless min (setq min 1))
(if (< max min) nil
(cons min (iota max (1+ min)))))
(defun multiple-p (n of)
"nがofの倍数かどうかを返す。"
(if (= (% n of) 0) t nil))
(defun eratos (max)
"エラトステネスのふるいでmaxまでの素数をリストで返す。"
(let ((lst (remove 1 (iota max))))
(dolist (s (remove-if '(lambda (x) (> x (sqrt max))) lst))
(delete-if '(lambda (x) (cond ((= x s) nil)
((multiple-p x s) t))) lst))
lst))
;; 結果
(print (eratos 211))
(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment