diff --git a/.editorconfig b/.editorconfig index 9021be4e7..57ac4d5a0 100644 --- a/.editorconfig +++ b/.editorconfig @@ -128,6 +128,11 @@ indent_size = 2 indent_style = space indent_size = 4 +# Factor +[*.factor] +intent_style = space +indent_size = 2 + #Lua [*.lua] indent_style = space diff --git a/book.json b/book.json index 74247a162..1665a1102 100644 --- a/book.json +++ b/book.json @@ -144,6 +144,10 @@ "lang": "f90", "name": "Fortran90" }, + { + "lang": "factor", + "name": "Factor" + }, { "lang": "ws", "name": "Whitespace" diff --git a/contents/euclidean_algorithm/code/factor/euclid.factor b/contents/euclidean_algorithm/code/factor/euclid.factor new file mode 100644 index 000000000..e822d1105 --- /dev/null +++ b/contents/euclidean_algorithm/code/factor/euclid.factor @@ -0,0 +1,32 @@ +: euclid- ( a b -- gcd ) + [ abs ] bi@ + [ 2dup = ] + [ + ! make sure the lower number is deeper + 2dup >= [ swap ] when + over - + ! leaves us with stack { } + ] + until + ! we have the GCD twice now, drop one + drop +; + +: euclid% ( a b -- gcd ) + [ abs ] bi@ ! take both absolute values + [ dup zero? ] ! check if `b` (on top) is 0 + [ + ! a b -> a b b -> b a b -> b a%b + dup -rot mod + ] + until + ! the zero is on top, so get rid of it + drop +; + +42 56 euclid% . ! 14 +48 180 euclid% . ! 12 + +42 56 euclid- . ! 14 +48 180 euclid- . ! 12 + diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index 985968792..0afd66038 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -41,6 +41,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:13-24, lang="nim"](code/nim/euclid_algorithm.nim) {% sample lang="f90" %} [import:1-19, lang="fortran"](code/fortran/euclidean.f90) +{% sample lang="factor" %} +[import:1-13, lang="factor"](code/factor/euclid.factor) {% sample lang="ws" %} [import, lang="whitespace"](code/whitespace/euclidian_sub.ws) {% sample lang="scala" %} @@ -98,6 +100,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:1-11, lang="nim"](code/nim/euclid_algorithm.nim) {% sample lang="f90" %} [import:21-34, lang="fortran"](code/fortran/euclidean.f90) +{% sample lang="factor" %} +[import:15-25, lang="factor"](code/factor/euclid.factor) {% sample lang="ws" %} [import, lang="whitespace"](code/whitespace/euclidian_mod.ws) {% sample lang="scala" %} @@ -160,6 +164,8 @@ The Euclidean Algorithm is truly fundamental to many other algorithms throughout [import, lang="nim" %](code/nim/euclid_algorithm.nim) {% sample lang="f90" %} [import, lang="fortran"](code/fortran/euclidean.f90) +{% sample lang="factor" %} +[import, lang="factor"](code/factor/euclid.factor) {% sample lang="ws" %} Here is a readable version of the algorithms with comments. First, subtraction method: [import, lang="whitespace"](code/whitespace/euclidian_sub_comments.ws)