Skip to content
Prev Previous commit
Next Next commit
deal with negative args and zero
  • Loading branch information
Ken Power committed Oct 3, 2018
commit 53763f11f043197afa8bc4fadd2249b0a6054155
22 changes: 12 additions & 10 deletions contents/euclidean_algorithm/code/scala/euclidean.scala
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
object Euclid {

def euclid(a: Int, b: Int):Int =
(a,b) match{
case (x, y) if x < y => euclid(x, y-x)
case (x, y) if x > y => euclid(x-y, y)
def euclid(a: Int, b: Int): Int =
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you rename it to euclid_sub?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. You're concerned about having Euclid and euclid in same namespace?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really, it's just more readable when you have 2 methods based on subtraction and modulo

(Math.abs(a), Math.abs(b)) match {
case (0, _) | (_, 0) => 0
case (x, y) if x < y => euclid(x, y - x)
case (x, y) if x > y => euclid(x - y, y)
case _ => a
}

def euclid_mod(a: Int, b: Int):Int =
b match{
def euclid_mod(a: Int, b: Int): Int =
b match {
case 0 => a
case _ => euclid_mod(b, a % b)
}

def main(args: Array[String]): Unit =
println(euclid(135749,27482))
println(euclid_mod(135749,27482))
def main(args: Array[String]): Unit = {
println(euclid(151 * 899, 151 * 182))
println(euclid_mod(151 * 899, 151 * 182))
}

}
}