find the least common multiple of a list of numbers in go

Here's an implementation of a function called lcmOfList that takes in a slice of integers and returns the least common multiple of all the integers in the slice:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    nums := []int{4, 6, 8, 10}
    lcm := lcmOfList(nums)
    fmt.Println(lcm) // Output: 120
}

func lcmOfList(nums []int) int {
    if len(nums) == 2 {
        return lcm(nums[0], nums[1])
    } else if len(nums) > 2 {
        return lcm(nums[0], lcmOfList(nums[1:]))
    }
    return nums[0]
}

func lcm(a, b int) int {
    return int(math.Abs(float64(a*b)) / float64(gcd(a, b)))
}

func gcd(a, b int) int {
    for b != 0 {
        a, b = b, a%b
    }
    return int(math.Abs(float64(a)))
}
556 chars
33 lines

The lcmOfList function recursively calculates the LCM of the numbers in the slice. It does this by first checking if there are only two numbers left in the slice, and if so, it uses the lcm function to find their LCM. If there are more than two numbers, it calls lcm on the first two numbers in the slice and the LCM of the rest of the numbers in the slice (recursively). The lcm function uses the formula LCM(a, b) = abs(a * b) / GCD(a, b) to calculate the LCM of two numbers, and the gcd function calculates the GCD of two numbers using the Euclidean algorithm.

related categories

gistlibby LogSnag