Euler Project#9(Pythagorean三胞胎)在Clojure
-
24-10-2019 - |
题
有人有任何建议以使其更加笨拙吗?
(use 'clojure.test)
(:import 'java.lang.Math)
(with-test
(defn find-triplet-product
([target] (find-triplet-product 1 1 target))
([a b target]
(let [c (Math/sqrt (+ (* a a) (* b b)))]
(let [sum (+ a b c)]
(cond
(> a target) "ERROR"
(= sum target) (reduce * (list a b (int c)))
(> sum target) (recur (inc a) 1 target)
(< sum target) (recur a (inc b) target))))))
(is (= (find-triplet-product 1000) 31875000)))
解决方案
这 Clojure-euluer项目 有几个程序供您参考。
其他提示
我个人使用了该算法(我发现它描述了 这里):
(defn generate-triple [n]
(loop [m (inc n)]
(let [a (- (* m m) (* n n))
b (* 2 (* m n)) c (+ (* m m) (* n n)) sum (+ a b c)]
(if (>= sum 1000)
[a b c sum]
(recur (inc m))))))
在我看来,复杂得多:-)
不隶属于 StackOverflow