开发者

Project Euler #9 (Pythagorean triplets) in Clojure

开发者 https://www.devze.com 2023-01-02 08:30 出处:网络
My answer to this problem feels too much like these solutions in C. Does anyone have any advice to make this more lispy?

My answer to this problem feels too much like these solutions in C.

Does anyone have any advice to make this more lispy?

(use 'clojure.test)
(:import 'java.l开发者_运维问答ang.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)))


The clojure-euluer-project has several programs for you to reference.


I personally used this algorithm(which I found described 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))))))

Seems to me much less complicated :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消