编写以下代码来检查数字是否为素数是一种更正确的函数方式:
(defn prime? [n]
(loop [k 2]
(cond
(< k n) (if (not= 0 (mod n k))
(recur (inc k))
(println n "is not prim"))
:else (println n "is prim"))))
答案 0 :(得分:8)
无论您使用哪种算法来测试素数,&#34;正确的功能方式&#34;将conf
函数返回$cols = 10;
$rows = 10;
$number = 0;
$number2 = 0;
echo "<table border=\"1\">";
for ($r = 0; $r <= $rows; $r++){
echo('<tr>');
if ($r == 0) {
for ($i = 0; $i < $rows; $i++) {
echo('<th>' .$number2++.'</th>');
}
}
for ($c = 0; $c <= $cols; $c++){
if ($c == 0) {
echo('<th>' .$number++.'</th>');
} else if ($r != 0) {
echo( '<td>' .$c*$r.'</td>');
}
}
echo('</tr>');
}
echo "</table>";
或prime?
。就目前而言,您的函数返回true
并具有副作用(打印出来的东西)。
然后,您可以false
检查特定号码,并将副作用限制在该单一语句中。
答案 1 :(得分:6)
使用标准库函数的简单方法,例如every?
和range
:
(defn divisible? [a b]
(zero? (mod a b)))
(defn prime? [n]
(and (> n 1) (not-any? (partial divisible? n) (range 2 n))))
并将I / O重构为一个单独的函数以便更好地重用:
(defn format-primality [n]
(str n " " (if (prime? n) "is prim" "is not prim")))
(def print-primality
(comp println format-primality))
示例:
user=> (map (fn [n] [n (prime? n)]) (range 1 15))
([1 false] [2 true] [3 true] [4 false] [5 true] [6 false] [7 true]
[8 false] [9 false] [10 false] [11 true] [12 false] [13 true] [14 false])