Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to check if a number is evenly divisible by another?

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?

like image 310
pimvdb Avatar asked Feb 13 '11 18:02

pimvdb


People also ask

How do you check if a number is evenly divisible by another number?

Use 'Mod' which returns the remainder of number1 divided by number2. So if remainder is zero then number1 is divisible by number2. e.g.

How do you find divisible evenly?

Evenly divisible means that you have no remainder. So, 20 is evenly divisible by 5 since 20 / 5 = 4. Though, 21 is not evenly divisible by 5 since 21 / 5 = 4 R 1, or 4.2.

How do you quickly determine if a number is divisible by 3?

A number is divisible by 3 if sum of its digits is divisible by 3. Illustration: For example n = 1332 Sum of digits = 1 + 3 + 3 + 2 = 9 Since sum is divisible by 3, answer is Yes.


1 Answers

Use Mod:

Function isDivisible(x As Integer, d As Integer) As Boolean
    Return (x Mod d) = 0
End Function
like image 106
gor Avatar answered Oct 25 '22 12:10

gor