2010-06-03 11 views
6

Meine Antwort auf diese problem fühlt sich zu sehr wie diese solutions in C.Projekt Euler # 9 (pythagoräische Drillinge) in Clojure

Hat jemand einen Rat, um das lispy zu machen?

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

Antwort

4

ich diesen Algorithmus persönlich in Anspruch genommen (was ich beschrieben here gefunden):

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

mir scheint viel weniger kompliziert :-)