dongqiao8502 2016-03-03 03:19
浏览 51

如何在不使用“ /”和“%”的情况下有效地获得商和余数?

I have implemented a simple function which returns the quotient and remainder when the divisor is the power of 10:

func getQuotientAndRemainder(num int64, digits uint) (int64, int64) {
    divisor := int64(math.Pow(10, float64(digits)))
    if num >= divisor {
        return num / divisor, num % divisor
    } else {
        return 0, num
    }
}

Just curious, except using directly / and % operators, is there any better algorithm to get the the quotient and remainder? Or only in the case when the divisor is the power of 10?

  • 写回答

2条回答 默认 最新

  • doupingpeng7567 2016-03-03 11:14
    关注
    return num / divisor, num % divisor
    

    The "algorithm" is sound and written in arguably the best way possible: expressively. If anything, this part of your code may be overly complicated:

    int64(math.Pow(10, float64(digits)))
    

    Converting to and from float64 is arguably sub-optimal. Also, 10 to the power of anything greater than 18 will overflow int64. I suggest you add a sanity check and replace the code with a multiplying loop and measure its performance.

    But then: if performance is your concern, just implement it in assembly.

    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改