Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Way to check to see if a number is odd or even??? 1

Status
Not open for further replies.

trifest

Programmer
Sep 5, 2002
52
US
I'm trying to determine if the number is odd or even to do my median function that i posted about before. What i'm trying to do is find the record count and then divide by 2 and depending if it's odd or even either go directly to the median or if even then take the average of the 2 middle records. Thanks for the help
 
if int(nNumber/2)*2 = nNumber
? Even
else
? Odd
endif


This will work. The idea is that if you take the integer value of a number divided by 2 and multiply it by 2, it will be the original number if it was even. Otherwise, the integer value of it will lose something and multiplying it by 2 will not result in the original number.
Don
dond@csrinc.com

 
nvar = 2
if nvar%2 > 0
nvar is even
else
nvar is odd
endif Attitude is Everything
 
trifest:

Try - mod(x,2).

if x is even mod(x,2) will return 0; if odd 1.

Note: if x is 0, mod(x,2) will also return 0.

Darrell

p.s. the mod() command works great for in number of list manipulation functions. eg. determine where to split an array into 12 buckets? mod(alen(array,1),12) tells you whether the buckets will be equally sized or if you'll have to fudge.

'We all must do the hard bits so when we get bit we know where to bite' :)
 
darrellblackhawk

% performs the same as mod(). % is an old operator from C, C++ Attitude is Everything
 
Danceman:

I know :) I just like Mod() because it's easy for me to spot in code
'We all must do the hard bits so when we get bit we know where to bite' :)
 
I don't know the performance of mod but I guess bitand would perform faster if this would be an issue because I think that bitand will not do any mathematics that mod has to do...
Code:
IF BITAND(nVar,1) = 0
  && nVar is even
ELSE
  && nVar is odd
ENDIF

Andreas
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top