0
How can you find whether a number is odd or even in a different way(other than (x%2==0))?
The main aim of this question is to find different unknown logics to find numbers are even or not!!
4 Answers
+ 1
Is this a question or a challenge?
The challenge has been posed before:
https://www.sololearn.com/post/1723667/?ref=app
+ 1
# Using the bitwise AND operator (&)
# The least significant bit (rightmost bit) of an even number is always 0.
# The least significant bit of an odd number is always 1.
# Performing a bitwise AND with 1 isolates this last bit.
if (value & 1) == 0:
print(f"'{value}' is an EVEN integer.")
else:
print(f"'{value}' is an ODD integer.")
+ 1
Uae floor division to divide by 2. Then multiply by 2. The result will be an even number. If the result matches the original number, then the original number was even.
if (value//2)*2 == value:
print("Even")
else:
print("Odd")
+ 1
Shift bits rightward once to lose the rightmost bit. Then shift back leftward and compare the original value. If they are the same then the rightmost bit was 0, and therefore it is an even number.
if (value>>1<<1 == value):
print("Even")
else:
print("Odd")