How to judge int number odd or even? (binary path)

I want to use basic knowledge to improve code performance. I know this in binary. when the last digit of a number is 1, it is an odd number. 0 is an even number. How to use this method to estimate int number in python? Does this python provide any inline method?

+6
source share
5 answers

And this is from 1:

0000101001000101 0000000000000001 & __________________ 0000000000000001 

If you get 1 , the number will be odd. If you get 0 , the number will be even. Although this works, I would use the modulo operator instead:

 >>> 8888 % 2 0 >>> 8881 % 2 1 

It works the same, just as fast and looks better:

 In [65]: %timeit random.randint(1, 1000000) & 1 == 0 1000000 loops, best of 3: 1.02 us per loop In [66]: %timeit random.randint(1, 1000000) % 2 == 0 1000000 loops, best of 3: 1.03 us per loop 
+12
source

You can & number and 1, if you get 0 , then the number is even, 1 means the number is odd.

 >>> 2 & 1 0 >>> 3 & 1 1 
+3
source

** PITON: LITTLE SIGNIFICANT BIT METHOD **

 >>> def is_odd(i): return bool(i & 1) >>> def is_even(i): return not is_odd(i) >>> [(j, is_odd(j)) for j in range(10)] [(0, False), (1, True), (2, False), (3, True), (4, False), (5, True), (6, False), (7, True), (8, False), (9, True)] >>> [(j, is_even(j)) for j in range(10)] [(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7, False), (8, True), (9, False)] >>> 

See if this can help you or not.

Explanation:
Check if the integer is even or odd. There are several ways to solve this problem: use even and odd predicates if the language provides them. Check the smallest significant digit. With binary integers, I'm bitwise and 1 is 0 iff I'm even or 1 if f is odd. Divide me by 2. The remainder is 0 if I'm even. The remainder is +1 or -1 if f is odd. Use modular congruences: I ≡ 0 (mod 2) if I'm even. i ≡ 1 (mod 2) if i am odd.

+2
source

You can simply use the & operator to check if the least significant bit is set;

 a = 77 is_odd = bool(a & 1) print is_odd # Prints True a = 64 is_odd = bool(a & 1) print is_odd # Prints False 
+1
source
 # Modular Congruencies # >> def is_even(i): return (i % 2) == 0 >>> is_even(1) False >>> is_even(2) True >>> 
0
source

Source: https://habr.com/ru/post/944305/


All Articles