Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler #9 (Pythagorean triplets) in Clojure

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.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)))
like image 953
dbyrne Avatar asked Jun 03 '10 15:06

dbyrne


2 Answers

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

like image 126
Yin Zhu Avatar answered Oct 02 '22 00:10

Yin Zhu


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

like image 37
Bozhidar Batsov Avatar answered Oct 01 '22 22:10

Bozhidar Batsov