[英]How can I get this function to work in Clojure?
I am a new learner in Clojure and working on this function no-divisors?
我是 Clojure 的新学习者,正在研究此
no-divisors?
函数no-divisors?
, where it should return true if none of the numbers between 2 and √𝑛 divide n, and false otherwise. ,如果 2 和 √𝑛 之间的任何数字都不能整除 n,则返回 true,否则返回 false。 I also need to use 2 functions inside
no-divisors
.我还需要在
no-divisors
使用 2 个函数。 First one is get-divisors
which takes a number n as input and returns the all the numbers between 2 and √𝑛 inclusive.第一个是
get-divisors
,它以数字 n 作为输入并返回 2 和 √𝑛 之间的所有数字。 The second function is Divides?
第二个函数是
Divides?
returns true if x divides n and false otherwise.如果 x 除以 n 则返回真,否则返回假。
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
任何建议,我将不胜感激
Note that range
is not inclusive on the far end.请注意,远端不包括
range
。
So your get-divisors should be:所以你的 get-divisor 应该是:
(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.然后用 9 调用
no-divisors
将返回 false。
When I copy and paste your definitions of Divides?当我复制和粘贴您对除法的定义时? and no-divisors?
和无除数? into a Clojure REPL, then call (no-divisors? 9), it returns false.
进入 Clojure REPL,然后调用 (no-divisors? 9),它返回 false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.