Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the modulus operator behave differently in Perl and PHP?

I've this PHP function which does not work for negative numbers:

function isOdd($num) 
{
   return $num % 2 == 1; 
}

but it works for positive number.

I have this Perl routine which does the exact same thing and works for negative number also

sub isOdd()
{
  my ($num) = @_;
  return $num % 2 == 1;
}

Did I make any mistake in translating the function ? or is it PHP bug ?

like image 815
user640527 Avatar asked Mar 02 '11 04:03

user640527


1 Answers

In PHP the sign of the result of x % y is the sign of dividend which is x but
in Perl it is the sign of the divisor which is y.

So in PHP the result of $num % 2 can be be either 1, -1 or 0.

So fix your function compare the result with 0:

function isOdd($num) { 
  return $num % 2 != 0; 
}
like image 177
codaddict Avatar answered Nov 15 '22 20:11

codaddict