PDA

View Full Version : Odd or Even


tflaherty
2005-05-19, 05:26 PM
Is there a quick & easy way to test the user's input to a getint function to see if the number is odd or even.

BTW negative numbers aren't allowed at this getint call.


Thanks

scwegner
2005-05-19, 05:37 PM
Pick one:

(defun IsEven ( x )
(zerop (rem x 2))
)

(defun IsEven ( x )
(/= 1 (logand x 1))
)

t-bone67
2005-05-19, 06:13 PM
OK, that's simple, but now I'm not sure how to fit it into my code.

Here's what I'm trying to do.

The routine is drawing cabinets, it prompts for the user to enter number of cabinets. I want to check if this number is even for it to draw the cabinets one way or if it's odd to draw them another way. So here's what I've got:

(setq NC (getint "\nSpecify number of cabinets: ")

this is where it should test for odd or even so I think it should be something like

(if NC is even
(progn

(do a bunch of stuff for even number of cabinets)
) end of progn

(progn

(do a bunch of stuff for odd number of cabinets)
)end progn

scwegner
2005-05-19, 06:21 PM
Both of those snippets return true if the number is even so your code would be:


(if
(/= 1 (logand x 1));test
(do stuff for even);true
(do stuff for odd);else
);if

madcadder
2005-05-19, 06:28 PM
(defun IsEven ( x )
(zerop (rem x 2))
)
OK... so the zerop will need a SETQ and that answer will need a (IF (= SETQ NIL) ) to compare?

And... How does the dividing by 2 help? What if X=64? Doesn't the REM just divide that one time only for an answer of SETQ=32?
(rem x 2 2) would equal SETQ=16
Correct?

I've got to be missing something.

scwegner
2005-05-19, 06:40 PM
OK... so the zerop will need a SETQ and that answer will need a (IF (= SETQ NIL) ) to compare?

And... How does the dividing by 2 help? What if X=64? Doesn't the REM just divide that one time only for an answer of SETQ=32?
(rem x 2 2) would equal SETQ=16
Correct?

I've got to be missing something. Yes, you need to set x to whatever you need to test. To prevent a nil value, he could make it:

(initget 1)
(setq NC (getint "\nSpecify number of cabinets: "))


As for how it works, REM returns the remainder, not the result of the division. So all you need to do is test if dividing the number by two results in a remainder of 0 or not. This method only works with integers though.

tflaherty
2005-05-19, 07:12 PM
Awesome!!!

Thanks BIG DAUG

kennet.sjoberg
2005-05-20, 07:27 AM
Is there a quick & easy way to test the user's input to a getint function to see if the number is odd or even.
INTeger value division give You the answer 1 or 0
(defun Odd_OR_Even ( value / )
(- value (* (/ value 2 ) 2 ) )
)
You can NOT use REAL value division

: ) Happy Computing !

kennet

CAB2k
2005-05-21, 01:34 AM
(defun IsEven ( x )
(zerop (rem (fix x) 2))
)