A Pythagorean triplet is a set of three natural numbers, a b c, for which,
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
(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