Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to judge a int number odd or even? (the binary way)

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?

like image 735
A Phototactic Coder Avatar asked May 05 '13 07:05

A Phototactic Coder


People also ask

How do you know if a binary number is odd or even?

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).

What is the best way to check if an integer is even or odd?

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.

How do you know if a binary number is odd or even Python?

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.

How does Python know if a number is even or 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.


2 Answers

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)
like image 152
Blender Avatar answered Sep 28 '22 03:09

Blender


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
like image 22
Nolen Royalty Avatar answered Sep 28 '22 02:09

Nolen Royalty