TheApprentice
TheApprentice

Reputation: 45

Clojure - Inclusive Range

I am using Clojure to do the following task -

Write a function named get-divisors which takes a number n as input and returns the all the numbers between 2 and √𝑛 inclusive

I have this code so far, that seems to be working as expected:

  (defn get-divisors [n]
   (str (range 2 (Math/sqrt n))))

The user inserts and input and the code shall display all numbers between 2 and the square root of that particular number. (I know! get-divisors is a horrible name for the function)

I type (get-divisors 101) I get the following output "(2 3 4 5 6 7 8 9 10)" which is correct.

However, the issue is when I use the number 4 I get a result of nil or () when I should in-fact get 2. Or when I enter 49 I should get all numbers between 2 and 7 but I only get all the numbers between 2 and 6.

I have searched online for some information. I am new to Clojure however, the information on this programming seems to be scarce as opposed to the likes of Java, JavaScript. I have read another thread which was based on a similar situation to mind, however, the suggestions/answers didn't work for me unfortunately.

I would appreciate any help. Thank you.

Upvotes: 1

Views: 248

Answers (1)

Alan Thompson
Alan Thompson

Reputation: 29966

Please see the Clojure CheatSheet. range does not include the upper bound. So, in general, you probably want something like

(range 2 (inc n)) 

or in your case

(range 2 (inc (Math/floor (Math/sqrt n))))

Also check out http://clojure.org

Upvotes: 3

Related Questions