in reply to Checking for odd/even number

It should be noted that perl is one of the few languages that computes mod of negative numbers properly. This means that the above algorithm will work fine in Perl for all integers but will work (for example) in C only for non-negative integers. Also the basic mod algorithm needs further enhancement to handle real numbers properly (needing to be able to reply "neither odd nor even"). It would be very interesting to hear how this algorithm performs in other languages (Python, Java, TCL, etc..).
Language Code Output
perl
for($c=-3;$c<4;$c++){ printf("%d %d\n",$c,$c % 2); }
-3 1
-2 0
-1 1
 0 0
 1 1
 2 0
 3 1
C/C++
int c; for(c=-3;c<4;c++){ printf("%d %d\n",c,c%2); }
-3  -1
-2   0
-1  -1
 0   0
 1   1
 2   0
 3   1

Replies are listed 'Best First'.
RE: Re: Checking for odd/even number
by rjimlad (Acolyte) on May 28, 2000 at 22:02 UTC
    Yes. $a % 2 ...effectively is is_odd($a), eg: printf $a%2?"odd\n":"even\n"; ...or whatever :)
RE: Re: Checking for odd/even number
by merlyn (Sage) on May 28, 2000 at 21:47 UTC
RE: Re: Checking for odd/even number
by mdillon (Priest) on May 29, 2000 at 08:45 UTC
    thanks for the tip. i'm sure this would have bitten me in the ass sooner or later, as i am occasionally silly enough to use a language other than perl.