Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and operator:
if x & 1:
return 'odd'
else:
return 'even'
Using Bitwise AND operator
- The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
- If a number is odd
& (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.