Reputation: 23
I am a new learner in Clojure and working on this function no-divisors?
, where it should return true if none of the numbers between 2 and √𝑛 divide n, and false otherwise. I also need to use 2 functions inside no-divisors
. First one is get-divisors
which takes a number n as input and returns the all the numbers between 2 and √𝑛 inclusive. The second function is Divides?
returns true if x divides n and false otherwise.
This is what I tried :
(defn Divides? [a b]
(zero? (mod b a)))
(defn get_divisors [n]
( range 2 (Math/sqrt n)))
(println "get divisors" (get_divisors 101))
output :get divisors (2 3 4 5 6 7 8 9 10)
(defn no-divisors? [n]
(->> (get_divisors n)
(filter #(Divides? % n))
empty?))
(println "no-divisors"(no-divisors? 9))
//output :expected :false current: true
I am expecting the result to be false but it is not. Any suggestions guys I would be appreciated
Upvotes: 1
Views: 114
Reputation: 1976
Note that range
is not inclusive on the far end.
So your get-divisors should be:
(defn get_divisors [n]
(range 2 (inc (int (Math/sqrt n)))))
(defn no-divisors? [n]
(->> (get_divisors n)
(filter #(Divides? % n))
empty?))
Then calling no-divisors
with 9 will return false.
Upvotes: 2
Reputation: 1516
When I copy and paste your definitions of Divides? and no-divisors? into a Clojure REPL, then call (no-divisors? 9), it returns false.
Upvotes: 0