Smallest Multiple by GoLang

来源:互联网 发布:淘宝购买steam游戏 编辑:程序博客网 时间:2024/06/04 23:28

My answer gives a general algorithm to deal with this problem via golang, and it produces the smallest positive number that is evenly divisible by all of the numbers from 1 to N. However, the overflow problem should be considered well by yourself in case of big int. Any question or suggestion, feel free to contact me.

func SmallestMultiple(n int) int {    primeLst := []int{}    factorCntMap := make(map[int]int)    for i := 2; i <= n; i++ {        tag := true        tmp := i        for _, j := range primeLst {            if tmp%j == 0 {                tag = false                cnt := 0                for tmp%j == 0 {                    tmp /= j                    cnt++                }                if cnt > factorCntMap[j] {                    factorCntMap[j] = cnt                }            } else if tmp == 1 {                break            }        }        if tag == true {            primeLst = append(primeLst, i)            factorCntMap[i] = 1        }    }    res := 1    for k, v := range factorCntMap {        for i := 0; i < v; i++ {            res *= k        }    }    return res}
原创粉丝点击