2

p-seq: Receives two integer arguments, “from” and “to”, and this method should return a sequence containing only the numbers given by is-p function between “from” and “to”. The current code that I have written only prints out all the numbers between "from" and "to". I want p-seq to return a sequence.

is-p: checks and returns true if a number is a prime number otherwise returns false.

(defn p-seq [from to]
  (loop [count from]
    (if (> count to)
      (println "")
      (do
        (def seqf (is-p count))
          (if(= seqf true)
            (print count " ")
            )
  (recur (inc count))))))

Any help appreciated. Thank you.

2 Answers 2

1

You simply can use filter function on sequence, filter is applied on each element

given is-p function that checks prime number,

user=> (filter is-p (range 1 20))
(2 3 5 7 11 13 17 19)

So, your p-seq function looks like,

user=> (defn p-seq [from to]
          (filter is-p (range from to)))
#'user/p-seq

user=> (p-seq 100 200)
(101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199)

references

https://clojuredocs.org/clojure.core/range

https://clojuredocs.org/clojure.core/filter

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Note the other answer too about (range x y) is actually [x y-1], if you want y to be included do something like (range from (+ 1 to)), clojuredocs.org/clojure.core/range describes it as well
1

Since you have a predicate function is-prime? you could simply use it to filter the range of all numbers between from and to:

(filter is-prime? (range 100 200))
=> (101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199)

Note the upper bound argument to range is exclusive.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.