-6

find even or odd number without modulo operator in php

I am having problem to find even or odd numbers without modulo sign. so that i cant prepare my code.

3 Answers3

2

One option is diving the number by 2. Use is_int to check if the result is an integer. If it is, it is even. Otherwise, it is odd.

$number = 6;
if ( is_int( $number / 2 )  ) {
    echo "EVEN";
} else {
    echo "ODD";
}
Eddie
  • 26,593
  • 6
  • 36
  • 58
1

bitwise:

$number=1;

if($number&1){
  echo $number.' is odd';
}else{
  echo $number.' is even';
}
0

You could always use subtstr() and a conditional that checks whether the last digit is 1, 3, 5, 7 or 9. This can be simplified with in_array():

$number = 12345;
$last = substr($number, -1);

if (in_array($last, array(1, 3, 5, 7, 9))) {
  echo "odd";
}
else {
  echo "even";
}

And shrunk with a ternary:

echo in_array($last, array(1, 3, 5, 7, 9)) ? "odd" : "even";

This can be seen working here.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71