项目欧拉#9(毕达哥拉斯三胞胎)在Clojure

时间:2010-06-03 15:20:22

标签: clojure pythagorean

我对此problem的回答与solutions in C感觉太过分了。

有没有人有任何建议可以让它变得更加lispy?

(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)))

2 个答案:

答案 0 :(得分:7)

clojure-euluer-project有几个程序供您参考。

答案 1 :(得分:4)

我个人使用了这个算法(我发现它描述了here):

(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))))))

对我而言似乎不那么复杂: - )