【问题标题】:Fast way to check if a number is evenly divisible by another?检查一个数字是否可以被另一个整除的快速方法?
【发布时间】:2011-06-26 12:43:42
【问题描述】:

我想知道在 VB.NET 中检查可分性的最快方法是什么。

我尝试了以下两个功能,但感觉好像有更有效的技术。

Function isDivisible(x As Integer, d As Integer) As Boolean
     Return Math.floor(x / d) = x / d
End Function

我想出了另一个:

Function isDivisible(x As Integer, d As Integer) As Boolean
     Dim v = x / d
     Dim w As Integer = v
     Return v = w
End Function

这是一种更实用的方法吗?

【问题讨论】:

  • 第二个似乎很有效,只要它可以工作并且应该足以让 JIT 自动内联它

标签: vb.net numbers integer division


【解决方案1】:

使用“Mod”返回 number1 除以 number2 的余数。因此,如果余数为零,则 number1 可以被 number2 整除。

例如

Dim result As Integer = 10 Mod 5 ' 结果 = 0

【讨论】:

    【解决方案2】:

    使用mod operator

    【讨论】:

      【解决方案3】:

      使用Mod:

      Function isDivisible(x As Integer, d As Integer) As Boolean
          Return (x Mod d) = 0
      End Function
      

      【讨论】:

        猜你喜欢
        • 2015-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-23
        • 1970-01-01
        • 2011-01-06
        • 1970-01-01
        相关资源
        最近更新 更多