Reputation: 154928
I was wondering what the fastest way is to check for divisibility in VB.NET.
I tried the following two functions, but I feel as if there are more efficient techniques.
Function isDivisible(x As Integer, d As Integer) As Boolean
Return Math.floor(x / d) = x / d
End Function
Another one I came up with:
Function isDivisible(x As Integer, d As Integer) As Boolean
Dim v = x / d
Dim w As Integer = v
Return v = w
End Function
Is this a more practical way?
Upvotes: 8
Views: 51790
Reputation: 11658
Use Mod
:
Function isDivisible(x As Integer, d As Integer) As Boolean
Return (x Mod d) = 0
End Function
Upvotes: 36
Reputation: 595
Use 'Mod' which returns the remainder of number1 divided by number2. So if remainder is zero then number1 is divisible by number2.
e.g.
Dim result As Integer = 10 Mod 5 ' result = 0
Upvotes: 8