Search code examples
clojure

Clojure inclusive range? prime-seq print-top-primes


Prime-seq function not printing the largest number in a range between 2 inputs when it is prime and should be printed. Also, effecting print-top-primes as this too will not print the biggest number in a range if it is prime. Unsure how to include this number I think that the issue is in the prime-seq function and print-top-primes is experiencing the same issue because it makes a call to prime-seq. Any help would be greatly appreciated.

Ive changing the values in the :let of prime-seq, tried adding inclusive syntax the I found online but that either did nothing or returned an error so I removed it.

(defn prime-seq [from to]
        (for [i (range from to)
          :let [y (+ i 0)]
          :when (is-prime? i)]
        y))

(defn print-top-primes [from to]
  (doseq [i (take 10 (reverse (prime-seq from to)))]
    (println i))
  (printf "Total = %d\n" (reduce + (prime-seq from to))))

With the input (prime-seq 7 11) the expected output should be "7 11" but what I am getting is "7".

With the input: (print-top-primes 50 103) I would expect the output to be "103, 101, 97, 89, 83, 79, 73, 71, 67" but the output I am getting is "101, 97, 89, 83, 79, 73, 71, 67, 61".


Solution

  • Since range is not inclusive on its end argument. From the docs:

    Returns a lazy seq of nums from start (inclusive) to end (exclusive)

    You could simply increment end before use, using inc :

    (defn prime-seq [from to]
            (for [i (range from (inc to))
              :let [y (+ i 0)]
              :when (is-prime? i)]
            y))