Saturday, August 15, 2009

Euler Project Nine

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product 
abc.


My Solution

(defun enumerate-interval (low high) 
   (loop for i from low to high 
      collect i))
(defun Euler9v4()
  (mapcar #'(lambda(x)(/ (- 500000 (* 1000 x)) (- 1000 x))) 
              (remove-if-not #'(lambda(i)(zerop (rem (- 500000 (* 1000 i)) (- 1000 i))))
                                    (enumerate-interval 1 500))))

Others' Solutions
First Solution
(defun euler9 () 
(car 
(loop for a from 1 to 998 
append (loop for b from 1 to (- 999 a) 
append (let ((c (- 1000 a b))) 
(if (= (* c c) 
(+ (* a a) (* b b))) 
(list (* a b c)))))))) 


Second Solution

(defun project-euler-009 () 

(do* ((num 1000) 

(c (floor (/ num 3)) (1+ c)) 

(result)) 

((> c num) result) 

(do* ((b (floor (/ c 2)) (1+ b)) 

(a (- num (+ c b)) (- num (+ c b)))) 

((>= b c)) 

(when (>= a 0) 

(when (= (+ (* a a) (* b b)) (* c c)) 

(setf result (cons (* a b c) result)))) 

)))


Third Solution

(defun search-for-triple (c) 

    (loop for a from 0 to (- 1000 c) do 

        (let ((b (- 1000 (+ a c)))) 

            (if (> a b) (return-from search-for-triple))
(if (= (+ (* a a) (* b b)) (* c c)) (format t "~a ~a ~a~%" a b c)))))
  

(loop for c from 1000 downto 0 do
(search-for-triple c))


No comments:

Post a Comment