Find LCM in Go



In this tutorial, we will learn how to find the Least Common Multiple (LCM) of two numbers in Go. We will cover the basic concept of LCM and implement functions using both the mathematical formula and the Euclidean algorithm.


What is LCM

The Least Common Multiple (LCM) of two or more integers is the smallest positive integer that is divisible by each of the integers. For example, the LCM of 4 and 5 is 20.


Syntax

The syntax to find the LCM of two numbers in Go is:

func gcd(a, b int) int {
    for b != 0 {
        a, b = b, a % b
    }
    return a
}

func lcm(a, b int) int {
    return a * b / gcd(a, b)
}


Example 1: Finding the LCM of two numbers using the Euclidean algorithm

We can use the Euclidean algorithm to find the LCM of two numbers by first finding their GCD and then using the relationship between GCD and LCM.

For example,

  1. Define a helper function named gcd that takes two parameters a and b of type int and returns their GCD using the Euclidean algorithm.
  2. Define a function named lcm that takes two parameters a and b of type int.
  3. Calculate the LCM using the formula a * b / gcd(a, b).
  4. Return the calculated LCM.
  5. In the main function, call the lcm function with sample values and print the result.

Go Program

package main

import (
    "fmt"
)

func gcd(a, b int) int {
    for b != 0 {
        a, b = b, a % b
    }
    return a
}

func lcm(a, b int) int {
    return a * b / gcd(a, b)
}

func main() {
    // Find the LCM of 4 and 5
    result := lcm(4, 5)

    // Print the result
    fmt.Printf("LCM of 4 and 5 is %d\n", result)
}

Output

LCM of 4 and 5 is 20