【问题标题】:Project Euler #9 (Pythagorean triplets) in ClojureClojure 中的 Project Euler #9(毕达哥拉斯三胞胎)
【发布时间】:2010-06-03 15:20:21
【问题描述】:

我对这个problem 的回答感觉太像这些solutions in C

有没有人有什么建议可以让这个更简洁?

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我个人使用了这个算法(我发现描述了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))))))
      

      在我看来不那么复杂:-)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多