From 92db31e76aa74655e936fa254012723dc6fba5c7 Mon Sep 17 00:00:00 2001 From: Trashtalk Date: Fri, 10 Aug 2018 19:31:54 +0200 Subject: [PATCH] Made euclid-sub and -mod work with negatives and refactored. --- .../code/lisp/euclidean_algorithm.lisp | 33 +++++++++++++++++++ .../euclidean_algorithm.md | 6 ++++ 2 files changed, 39 insertions(+) create mode 100644 contents/euclidean_algorithm/code/lisp/euclidean_algorithm.lisp diff --git a/contents/euclidean_algorithm/code/lisp/euclidean_algorithm.lisp b/contents/euclidean_algorithm/code/lisp/euclidean_algorithm.lisp new file mode 100644 index 000000000..cff5ab29f --- /dev/null +++ b/contents/euclidean_algorithm/code/lisp/euclidean_algorithm.lisp @@ -0,0 +1,33 @@ +;;;; Euclid algorithm implementation + +(defun euclid-sub (a b) + (euclid-sub* (abs a) (abs b))) + +(defun euclid-sub* (a b) + (if (eq a b) + a + (if (> a b) + (euclid-sub* (- a b) b) + (euclid-sub* a (- b a))))) + +(defun euclid-mod (a b) + (if (zerop b) + (abs a) + (euclid-mod b (mod a b)))) + +(print + (euclid-sub (* 64 67) + (* 64 81))) +(print + (euclid-mod (* 128 12) + (* 128 77))) + +;; built-in function: (gcd 80 40) +;; quick test +(assert + (= (euclid-sub (* 64 67) (* 64 81)) + (gcd (* 64 67) (* 64 81)))) + +(assert + (= (euclid-mod (* 64 67) (* 64 81)) + (gcd (* 64 67) (* 64 81)))) diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index 7cfe043a5..712f90295 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -17,6 +17,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:3-16, lang="java"](code/java/EuclideanAlgo.java) {% sample lang="js" %} [import:15-29, lang="javascript"](code/javascript/euclidean_example.js) +{% sample lang="lisp" %} +[import:3-12, lang="lisp"](code/lisp/euclidean_algorithm.lisp) {% sample lang="py" %} [import:11-22, lang="python"](code/python/euclidean_example.py) {% sample lang="haskell" %} @@ -58,6 +60,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:18-26, lang="java"](code/java/EuclideanAlgo.java) {% sample lang="js" %} [import:1-13, lang="javascript"](code/javascript/euclidean_example.js) +{% sample lang="lisp" %} +[import:13-17, lang="lisp"](code/lisp/euclidean_algorithm.lisp) {% sample lang="py" %} [import:1-9, lang="python"](code/python/euclidean_example.py) {% sample lang="haskell" %} @@ -104,6 +108,8 @@ Program.cs [import, lang="java"](code/java/EuclideanAlgo.java) {% sample lang="js" %} [import, lang="javascript"](code/javascript/euclidean_example.js) +{% sample lang="lisp" %} +[import, lang="lisp"](code/lisp/euclidean_algorithm.lisp) {% sample lang="py" %} [import, lang="python"](code/python/euclidean_example.py) {% sample lang="haskell" %}