determin if a number is even or odd

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,530
Location
Lansing, MI; USA
Programming Experience
10+
what's the best way to determin if a number is even or odd?

Dim intNum As Integer = "23"
how would i have it check intNum and know it's odd?
 
use the modulo function.... forget what it is in .NET, but it was the mod keyword in VB6.

VB.NET:
If intNum Mod 2 <> 0 Then
 Messagebox.Show "Odd number"
Else
 Messagebox.Show "Even"
End If

-tg
 
Not that I am aware of.... and since it's a math operation, it's quick and fast.

-tg
 
*nod* ja, the maths stuff runs super quick... in some cases you might get numbers of a bizillion digits though... so would converting the number to a string and casing the last digit not perhaps be faster?
 
No...
It would be slower.... here's why:
Doing bit shifts on numeric data is faster than having to convert to a string. First space big enough for the string has to be created, then the number copied to that new location, changing the datatype along the way. Then you have to grab that last character, convert back to a number, and then do the bit shift.

Why not just cut that all out and do the bit shift in the first place (which is how mod works). IF you really want to do nuts, do the bit-shift yourself and check the result. (actualy, it might be a form of bit masking now that I think about it.).

-tg
 
That's the bit-masking/shifting I was talking about..... and the method we use in our app to determine security permissions.

-tg
 
hey everybody,
how about if i wanted to generate a random number between say 1 and 100, but only even numbers,

please help
thanx
 
fishtank said:
hey everybody,
how about if i wanted to generate a random number between say 1 and 100, but only even numbers,

please help
thanx
Then you'd generate a random number between say 1 and 50 then multiply it by 2.
 
thanx, i'm a total beginner, and i saw my prof generating random even numbers using mod function so i was trying to use that but got nowhere. your way seems so much easier.

thanks a LOT!!
 
You could use Mod something like this I guess:
VB.NET:
Dim myRandomNumber As Integer = myRandom.Next(1, 100 + 1)
Dim myEvenNumber As Integer = myRandomNumber - myRandomNumber Mod 2
That will include zero in the output set, so you would have to make an adjustment if you didn't want that, like make 2 the minimum or else make 100 the maximum and then add the difference instead of subtracting.
 
Back
Top