Saturday, 27 June 2015

Greatest Common Divisor and Least Common Multiple

For the greatest common divisor, BigInt implements a gcd method. From here, least common multiple can be implemented as follows:
object LeastCommonMultiple {

  def lcm(a: BigInt, b: BigInt): BigInt = a * b / a.gcd(b)

  def main(args: Array[String]): Unit = {
    println(lcm(3, 4))    
The above prints "12"

No comments:

Post a Comment