The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
I use the Mathematica 7.0 this time
Total[Table[Prime[n], {n, PrimePi[2000000]}]]
LISP Solution
(defun seq-list (min max)
(loop for i from min to max collect i))
(defun sieve (lst)
(let ((primes '())
(last (car (last lst))))
(loop while (and lst (> last (* (car lst) (car lst))))
do (let ((factor (car lst)))
(setq primes (cons factor primes))
(setq lst (remove-if
#'(lambda (n)
(= (mod n factor) 0))
(cdr lst)))))
(append (reverse primes) lst)))
(defun all-primes (limit)
(sieve (seq-list 2 limit)))
(defun euler10 ()
(reduce #'+ (all-primes 1000000)))
(loop for i from min to max collect i))
(defun sieve (lst)
(let ((primes '())
(last (car (last lst))))
(loop while (and lst (> last (* (car lst) (car lst))))
do (let ((factor (car lst)))
(setq primes (cons factor primes))
(setq lst (remove-if
#'(lambda (n)
(= (mod n factor) 0))
(cdr lst)))))
(append (reverse primes) lst)))
(defun all-primes (limit)
(sieve (seq-list 2 limit)))
(defun euler10 ()
(reduce #'+ (all-primes 1000000)))
Second Solution
(defun euler10 (&optional (sieve 1000000))
(let ((numbers (make-array sieve :initial-element t))
(upper-bound (isqrt (- sieve 1)))
(total 0))
(do ((i 2 (+ i 1))) ((> i upper-bound) 'done)
(when (svref numbers i)
(incf total i)
(do ((j (* i i) (+ j i))) ((> j (- sieve 1)) 'done)
(setf (svref numbers j) nil))))
(do ((i (+ 1 upper-bound) (+ i 1))) ((= i sieve) total)
(when (svref numbers i)
(incf total i)))))
(let ((numbers (make-array sieve :initial-element t))
(upper-bound (isqrt (- sieve 1)))
(total 0))
(do ((i 2 (+ i 1))) ((> i upper-bound) 'done)
(when (svref numbers i)
(incf total i)
(do ((j (* i i) (+ j i))) ((> j (- sieve 1)) 'done)
(setf (svref numbers j) nil))))
(do ((i (+ 1 upper-bound) (+ i 1))) ((= i sieve) total)
(when (svref numbers i)
(incf total i)))))
Third Solution
(defun solve-10 ()
(loop for i in (prime-numbers 999999) sum i))
(loop for i in (prime-numbers 999999) sum i))
(defun prime-numbers (n)
(let ((a (make-array (1+ n) :initial-element 0)))
; Search primes
(
(let ((a (make-array (1+ n) :initial-element 0)))
; Search primes
(
loop for i from 2 to n
when (zerop (aref a i)) do
(loop for j from (* i 2) to n by i do
(setf (aref a j)
(+ (aref a j) i))))
when (zerop (aref a i)) do
(loop for j from (* i 2) to n by i do
(setf (aref a j)
(+ (aref a j) i))))
; List of primes
(loop for i from 2 to n
when (zerop (aref a i))
collect i)))
(loop for i from 2 to n
when (zerop (aref a i))
collect i)))
No comments:
Post a Comment