fork download
  1. ; The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
  2. ; Find the sum of all the primes below two million.
  3. (set! *warn-on-reflection* true)
  4. (defn zero-multiples-of [n nums]
  5. (loop [new-nums nums mult-ix (- (* n n) 2)]
  6. (if (>= mult-ix (count nums)) new-nums
  7. (recur (assoc new-nums mult-ix 0) (+ n mult-ix)))))
  8.  
  9. (defn ith-p [nums target-ix]
  10. (loop [nums-found 0 vec-ix 0]
  11. (if (>= vec-ix (count nums)) nil
  12. (let [cur-num (nth nums vec-ix)]
  13. (if (and (pos? cur-num) (= nums-found target-ix)) cur-num
  14. (recur
  15. (if (pos? cur-num) (inc nums-found) nums-found)
  16. (inc vec-ix)))))))
  17.  
  18. (defn sieve-to [^Integer max]
  19. (loop [nums (vec (range 2 max)) i 0 p 2]
  20. (if (>= (* p p) max) nums
  21. (let [new-nums (zero-multiples-of p nums)]
  22. (recur new-nums (inc i) (ith-p new-nums (inc i)))))))
  23.  
  24. (println
  25. ;(zero-multiples-of 3 (vec (range 2 100)))
  26. ;(sieve-to 100)
  27. (time (reduce + (sieve-to 200000)))
  28. )
Success #stdin #stdout #stderr 2.3s 390144KB
stdin
Standard input is empty
stdout
"Elapsed time: 948.211372 msecs"
1709600813
stderr
prog.clj:22 recur arg for primitive local: p is not matching primitive, had: Object, needed: long
Auto-boxing loop arg: p