I wanna use basic knowledge to improve the efficiency of code. I know that in binary system. when the last digit of number is 1,this is a odd number.and 0 is even number. How to use this way to judge a int number in python? Is that python give any build-in method to do it?
If the last digit of a binary number is 1, the number is odd; if it's 0, the number is even. Ex: 1101 represents an odd number (13); 10010 represents an even number (18).
A number is even if, when divided by two, the remainder is 0. A number is odd if, when divided by 2, the remainder is 1.
With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
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.
AND it with 1:
0000101001000101
0000000000000001
&
__________________
0000000000000001
If you get 1
, the number is odd. If you get 0
, the number is even. While this works, I would use the modulo operator instead:
>>> 8888 % 2
0
>>> 8881 % 2
1
It's faster and more straightforward to read:
In [5]: numbers = [random.randint(1, 1000000) for n in range(100000)]
In [6]: %timeit [n & 1 == 0 for n in numbers]
11 ms ± 390 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [7]: %timeit [n % 2 == 0 for n in numbers]
8.05 ms ± 244 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
You can &
the number and 1, if you get 0
then the number is even, 1
means the number is odd.
>>> 2 & 1
0
>>> 3 & 1
1
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