How to calculate the least common multiple (LCM) of two integers in Go?

To calculate the least common multiple (LCM) of two integers in Go, you can use the following algorithm:

  1. Import the "math" package to access the "Max" function.
import "math"
  1. Create a function called "LCM" that takes two integers as parameters and returns an integer:
func LCM(a, b int) int { // Calculate the maximum of the two numbers max := math.Max(float64(a), float64(b)) // Loop through multiples of max to find the LCM for i := max; ; i += max { // Check if the current multiple is divisible by both numbers if i%a == 0 && i%b == 0 { return i // Return the LCM } } }
  1. Call the "LCM" function with the desired integers and store the result in a variable:
result := LCM(12, 18)

Here's the complete code example:

package main import ( "fmt" "math" ) func LCM(a, b int) int { max := math.Max(float64(a), float64(b)) for i := max; ; i += max { if i%a == 0 && i%b == 0 { return int(i) } } } func main() { result := LCM(12, 18) fmt.Println("LCM:", result) }

In this example, the LCM of 12 and 18 is calculated and printed as the output.