Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Nice, I like the optimization replacing the list, and just hunting for the next 'free' composite for the prime.

Teaching my kids coding, we also arrived at most of the other optimizations, in Janet:

  (defn primes-sieve []
    (fiber/new (fn []
      (yield 2) # the only even prime, yield it explicitly.
  
      (let [sieve (table/new (math/pow 2 12))]
        (loop [n :range [3 nil 2]]  # only odd numbers
          (if-let [current-composite (sieve n)]
            (do 
              (each prime-factor current-composite
                (let [next-composite-key (+ n (* 2 prime-factor))] # add 2*prime-factor, else composite would be even
                  (if-let [next-composite (sieve next-composite-key)]
                    (array/push next-composite prime-factor)
                    (put sieve next-composite-key @[prime-factor]))))
              (put sieve n nil))
            (do
              (yield n)
              (put sieve (* n n) @[n])) # next composite is n^2. Anything less is composite a smaller prime, already in the sieve
            ))))))



Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: