DEV Community

Discussion on: Odd or Even?

Collapse
 
krlv profile image
eugene kirillov

I would say modulus operator is too powerful for this task. All you need to do to determine whether the number is odd or even, is to check number's first bit: 0 for even number, 1 for odd:

function odd_or_even(array $integer_array): string {
    return array_sum($integer_array) & 1 ? 'odd' : 'even';
}

Sidenote on array_reduce performance: for arrays of length > 1000 elements, array_sum is faster than array_reduce by an order of magnitude.

Collapse
 
jamesrweb profile image
James Robb

Bitwise checks are smart but most people don’t understand them and explaining them would’ve made for a longer article so using modulus was easier to show and explain for a larger audience plus it works perfectly well for this use case.

On the performance point I agree but I don’t care much for it since there isn’t any performance issues arisen worth an implementation change “premature optimisation is the root of all evil” and all that.