Sieve of Eratosthenes Scheme

后端 未结 4 2082
青春惊慌失措
青春惊慌失措 2020-12-19 19:43

I\'ve been searching the web for an implementation of the Sieve of Eratosthenes in scheme and although I came up with a lot of content, none of them seemed to have made it l

4条回答
  •  孤城傲影
    2020-12-19 19:56

    (define (prime-sieve-to n)
      (let* ((sz (quotient n 2)) (sv (make-vector sz 1)) (lm (integer-sqrt n)))
        (for ((i (in-range 1 lm))) 
          (cond ((vector-ref sv i)
            (let ((v (+ 1 (* 2 i))))
              (for ((i (in-range (+ i (* v (/ (- v 1) 2))) sz v)))
                (vector-set! sv i 0))))))
        (cons 2
              (for/list ((i (in-range 1 sz)) 
                         #:when (and (> (vector-ref sv i) 0) (> i 0)))
                        (+ 1 (* 2 i))))))
    

    This is another one in racket dialect of scheme that works but for up to 100,000,000. Above that, I would not vouch for its efficiency.

提交回复
热议问题