How To

How to check if a number is even or odd?

0

Cowboy software 2020-06-10 15:27

How do I check if a number is even or odd
Thank you!!


Timo 2020-06-10 15:33

INPUT “NUMBER:”;NUM
IF NUM MOD 2=0 THEN
PRINT “EVEN”
ELSE
PRINT “ODD”
END IF

MOD divides and returns the rest. So if your number divided by 2 has no rest, it’s even.


Cowboy software 2020-06-10 16:01

Thank you very much it was very useful


was8bit 2020-06-11 06:51

Ah ha! This is much more clever than my approach...

IF X\2=X/2 THEN "even" ELSE "odd"


nwallen 2020-06-11 12:38

A bit more advanced.
You can also bit-wise operation: IF NUM AND 1 THEN ODD ELSE EVEN

ODD_NUM AND 1 results in 1 being returned. (3)11 AND 1 => 01
EVEN_NUM AND 1 results in 0 being returned. (4)100 AND 1 => 000

FOR Y = 1 TO 15
'make random number
NUM = RND(10000)+1
IF NUM AND 1 THEN
PRINT STR$(NUM)," ODD"
ELSE
PRINT STR$(NUM)," EVEN"
END IF
WAIT VBL
NEXT Y


was8bit 2020-06-11 16:15

Cool :)


Log in to reply.