sieve of eratosthenes pasted by anandamide on Wed May 11 06:19:32 2016

(use srfi-1)

(define sieve
  (lambda (max)
    (define cross-list ;crosses out every it'th item from lst starting at the first number in lst matching it
      (lambda (lst it)
	(map (lambda (x)
	       (cond ((eq? x it) x)
		     ((eq? x 0) 0)
		     ((integer? (/ x it)) 0)
		     (else x)))
	     lst)))
    (define nextnz ;gets next number in list thats not 0 and is greater than cur
      (lambda (lst cur)
	(cond ((null? lst) #f)
	      ((or (eq? (car lst) 0)
		   (eq? (car lst) cur)
		   (< (car lst) cur))
	       (nextnz (cdr lst) cur))
	    (else (car lst)))))
    (let loop ((n 2) (nums (cddr (iota max))))
      (cond ((< (* n n) max)
	     (loop (nextnz nums n) (cross-list nums n)))
	    (else (filter (lambda (x) (not (eq? 0 x))) nums))))))

(display (fold + 0 (sieve 2000000)))

forgot some documentation added by anandamide on Wed May 11 06:21:20 2016

(use srfi-1)

(define sieve
  (lambda (max)
    (define cross-list ;crosses out every it'th item from lst starting at the first number in lst matching it
      (lambda (lst it)
	(map (lambda (x)
	       (cond ((eq? x it) x)
		     ((eq? x 0) 0)
		     ((integer? (/ x it)) 0)
		     (else x)))
	     lst)))
    (define nextnz ;gets next number in list thats not 0 and is greater than cur
      (lambda (lst cur)
	(cond ((null? lst) #f)
	      ((or (eq? (car lst) 0)
		   (eq? (car lst) cur)
		   (< (car lst) cur))
	       (nextnz (cdr lst) cur))
	      (else (car lst)))))
    
    (let loop ((n 2) (nums (cddr (iota max)))) ;replaces every n item in nums starting from n in nums with 0 until n^2 is greater than max
      (cond ((< (* n n) max)
	     (loop (nextnz nums n) (cross-list nums n)))
	    (else (filter (lambda (x) (not (eq? 0 x))) nums))))))

(display (fold + 0 (sieve 2000000)))