[Golang] Calculate Least Common Multiple (LCM) by GCD


Find least common multiple (LCM) by greatest common divisor (GCD) via Go programming language.

We use the following formula to calculate LCM:

For a, b ∈ ℕ, a*b = LCM(a, b)*GCD(a, b)

To calculate GCD, see my previous post [1].

Run Code on Go Playground

package main

import (
      "fmt"
)

// greatest common divisor (GCD) via Euclidean algorithm
func GCD(a, b int) int {
      for b != 0 {
              t := b
              b = a % b
              a = t
      }
      return a
}

// find Least Common Multiple (LCM) via GCD
func LCM(a, b int, integers ...int) int {
      result := a * b / GCD(a, b)

      for i := 0; i < len(integers); i++ {
              result = LCM(result, integers[i])
      }

      return result
}

func main() {
      fmt.Println(LCM(10, 15))
      fmt.Println(LCM(10, 15, 20))
      fmt.Println(LCM(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
}

If you are not familiar with variadic function of Go, see my previous post [2].

Tested on Go Playground.


References:

[1][Golang] Greatest Common Divisor via Euclidean Algorithm
[2][Golang] Variadic Function Example - addEventListener
[3][Golang] Smallest Multiple - Problem 5 - Project Euler