Skip to content

Commit 285e3db

Browse files
kenpowerjiegillet
authored andcommitted
add Scala implementation for Euclidean (#427)
* add Scala example for Euclidean * deal with negative args and zero * deal with negative args and zero * rename function * change method name * fix typo
1 parent fc9947e commit 285e3db

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
object Euclid {
2+
3+
def euclid_sub(a: Int, b: Int): Int =
4+
(Math.abs(a), Math.abs(b)) match {
5+
case (0, _) | (_, 0) => 0
6+
case (x, y) if x < y => euclid(x, y - x)
7+
case (x, y) if x > y => euclid(x - y, y)
8+
case _ => a
9+
}
10+
11+
def euclid_mod(a: Int, b: Int): Int =
12+
(Math.abs(a), Math.abs(b)) match {
13+
case (_, 0) => a
14+
case (a, b) => euclid_mod(b, a % b)
15+
}
16+
17+
def main(args: Array[String]): Unit = {
18+
println(euclid_sub(151 * 899, 151 * 182))
19+
println(euclid_mod(151 * 899, 151 * 182))
20+
}
21+
22+
}

contents/euclidean_algorithm/euclidean_algorithm.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
4141
[import:13-24, lang="nim"](code/nim/euclid_algorithm.nim)
4242
{% sample lang="f90" %}
4343
[import:1-19, lang="fortran"](code/fortran/euclidean.f90)
44+
{% sample lang="scala" %}
45+
[import:3-8, lang="scala"](code/scala/euclidean.scala)
4446
{% sample lang="racket" %}
4547
[import:3-14, lang="lisp"](code/racket/euclidean_algorithm.rkt)
4648
{% endmethod %}
@@ -90,6 +92,8 @@ Modern implementations, though, often use the modulus operator (%) like so
9092
[import:1-11, lang="nim"](code/nim/euclid_algorithm.nim)
9193
{% sample lang="f90" %}
9294
[import:21-34, lang="fortran"](code/fortran/euclidean.f90)
95+
{% sample lang="scala" %}
96+
[import:10-14, lang="scala"](code/scala/euclidean.scala)
9397
{% sample lang="racket" %}
9498
[import:16-24, lang="lisp"](code/racket/euclidean_algorithm.rkt)
9599
{% endmethod %}
@@ -144,6 +148,8 @@ The Euclidean Algorithm is truly fundamental to many other algorithms throughout
144148
[import, lang="nim" %](code/nim/euclid_algorithm.nim)
145149
{% sample lang="f90" %}
146150
[import, lang="fortran"](code/fortran/euclidean.f90)
151+
{% sample lang="scala" %}
152+
[import, lang="scala"](code/scala/euclidean.scala)
147153
{% sample lang="racket" %}
148154
[import, lang="lisp"](code/racket/euclidean_algorithm.rkt)
149155
{% endmethod %}

0 commit comments

Comments
 (0)