The required code is provided below. num = int (input (“Enter any number to test whether it is odd or even: “) if (num % 2) == 0: print (“The number is even”) else: print (“The provided number is odd”) Output: Enter any number to test whether it is odd or even: 887 887 is odd.
In the above program, number % 2 == 0 checks whether the number is even. If the remainder is 0, the number is even. In this case, 27 % 2 equals to 1. Hence, the number is odd.
You were right in thinking mod was a good place to start. Here is an expression which will return true if $number
is even, false if odd:
$number % 2 == 0
Works for every integerPHP value, see as well Arithmetic OperatorsPHP.
Example:
$number = 20;
if ($number % 2 == 0) {
print "It's even";
}
Output:
It's even
Another option is a simple bit checking.
n & 1
for example:
if ( $num & 1 ) {
//odd
} else {
//even
}
Yes using the mod
$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);
While all of the answers are good and correct, simple solution in one line is:
$check = 9;
either:
echo ($check & 1 ? 'Odd' : 'Even');
or:
echo ($check % 2 ? 'Odd' : 'Even');
works very well.
(bool)($number & 1)
or
(bool)(~ $number & 1)
I did a bit of testing, and found that between mod, is_int
and the &
-operator, mod is the fastest, followed closely by the &-operator.
is_int
is nearly 4 times slower than mod.
I used the following code for testing purposes:
$number = 13;
$before = microtime(true);
for ($i=0; $i<100000; $i++) {
$test = ($number%2?true:false);
}
$after = microtime(true);
echo $after-$before." seconds mod<br>";
$before = microtime(true);
for ($i=0; $i<100000; $i++) {
$test = (!is_int($number/2)?true:false);
}
$after = microtime(true);
echo $after-$before." seconds is_int<br>";
$before = microtime(true);
for ($i=0; $i<100000; $i++) {
$test = ($number&1?true:false);
}
$after = microtime(true);
echo $after-$before." seconds & operator<br>";
The results I got were pretty consistent. Here's a sample:
0.041879177093506 seconds mod
0.15969395637512 seconds is_int
0.044223070144653 seconds & operator
Another option is to check if the last digit is an even number :
$value = "1024";// A Number
$even = array(0, 2, 4, 6, 8);
if(in_array(substr($value, -1),$even)){
// Even Number
}else{
// Odd Number
}
Or to make it faster, use isset()
instead of array_search
:
$value = "1024";// A Number
$even = array(0 => 1, 2 => 1, 4 => 1, 6 => 1, 8 => 1);
if(isset($even[substr($value, -1)]){
// Even Number
}else{
// Odd Number
}
Or to make it more faster (beats mod operator
at times) :
$even = array(0, 2, 4, 6, 8);
if(in_array(substr($number, -1),$even)){
// Even Number
}else{
// Odd Number
}
Here is the time test as a proof to my findings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With