To calculate the least common multiple (LCM) of two integers in Go, you can use the following algorithm:
import "math"
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
}
}
}
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.