2010-06-03 56 views
6

我對這個problem的答案感覺太像這些solutions in C項目歐拉#9(畢達哥拉斯三胞胎)在Clojure

有沒有人有任何建議,使這更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))) 

回答

7

clojure-euluer-project有幾個程序供您參考。

+0

大資源...感謝。 – dbyrne 2010-06-03 15:33:05

+0

+1鏈接! – 2010-06-04 14:17:37

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

在我看來,:-)更復雜