Re: Checking for odd/even number
by lhoward (Vicar) on May 28, 2000 at 21:26 UTC
|
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 |
| [reply] [d/l] [select] |
|
|
Yes.
$a % 2
...effectively is is_odd($a), eg:
printf $a%2?"odd\n":"even\n";
...or whatever :)
| [reply] [d/l] [select] |
|
|
| [reply] |
|
|
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.
| [reply] |
Re: Checking for odd/even number
by perlmonkey (Hermit) on May 28, 2000 at 11:07 UTC
|
And you can inline the if/else using the ? : operators.
print $_ % 2 ? "$_ is odd\n" : "$_ is even\n" for (1..5)
Results:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
| [reply] [d/l] |
|
|
how u gonna write your source code if u have to print odd and even number for less than 50 only using while statement for odd and for statement for even number:
Wondering.
| [reply] |
Re: Checking for odd/even number
by Anonymous Monk on May 28, 2000 at 09:19 UTC
|
if ($var % 2 == 1)
{
# odd
}
else
{
# even
}
| [reply] [d/l] |
|
|
Since for %2, possible results are 0 or 1, you can drop the equivalence as well:
if ($var%2) {
# odd
}
else {
# even
}
cLive ;-) | [reply] [d/l] |
RE: Checking for odd/even number
by cciulla (Friar) on May 28, 2000 at 19:15 UTC
|
Both perlmonkey's and AM's comments are right on the money, but I figured a futher explaination may be warranted.
perl's % operator is the "modulus" (aka "mod") operator -- in other words, it gives you an integer representation of the remainder of a division operation.
If X / Y divides evenly (that is to say, there's no remainder (or modulus)), the result of X % Y will be zero. | [reply] |
RE: Checking for odd/even number
by mikkoh (Beadle) on May 28, 2000 at 22:35 UTC
|
if($specified_number & 1){
print "Odd one!";
}
//MJH | [reply] |