Advertisement
bs9o

task2

Apr 1st, 2022
565
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ;task 2.1
  2.  
  3. (defn is-divisible-by? [n m]
  4.   (if (integer? (/ n m))
  5.     true
  6.     false))
  7.  
  8. (defn sieve
  9.   ([n]
  10.    (sieve n 2 '(2) (range 3 (inc n))))
  11.   ([n highest-prime primes numbers]
  12.    (if (> highest-prime (Math/sqrt n))
  13.      (concat primes numbers)
  14.      (let [rest-numbers (remove
  15.                                (fn [x]
  16.                                  (and
  17.                                    (is-divisible-by? x highest-prime)
  18.                                    (not (= x highest-prime))))
  19.                                numbers)]
  20.       (recur n (first rest-numbers)
  21.         (concat primes (list (first rest-numbers))) (rest rest-numbers))))))
  22.  
  23. (defn nth-prime [n] (nth (sieve (* n n)) (dec n)))
  24.  
  25. ;task 2.2
  26.  
  27. (defn lazy-sieve
  28.   ([highest-prime numbers]
  29.    (let [rest-numbers (remove
  30.                         (fn [x]
  31.                           (is-divisible-by? x highest-prime))
  32.                         numbers)]
  33.      (lazy-seq (cons highest-prime (lazy-sieve (first rest-numbers) rest-numbers))))))
  34.  
  35. (def primes (lazy-sieve 2 (iterate inc 2)))
Advertisement
RAW Paste Data Copied
Advertisement