加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Smallest Multiple by GoLang

发布时间:2020-12-16 18:05:31 所属栏目:大数据 来源:网络整理
导读: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 you

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读