Given a number and our task is to check number is Even or Odd using Python. Those numbers which are completely divisible by 2 or give 0 as the remainder are known as even number and those that are not or gives a remainder other than 0 are known as odd numbers.
Example:
Input: 2
Output: Even number
Input: 41
Output: Odd Number
Check Even or Odd Number using the modulo operator in Python
In this method, we use the modulo operator (%) to check if the number is even or odd in Python. The Modulo operator returns the remainder when divided by any number so, we will evaluate the x%2, and if the result is 0 a number is even otherwise it is an odd number.
Python3
x = 24 if x % 24 = = 0 : print (x, "Is Even Number" ) else : print (x, "Is Odd Number" ) y = 19 if y % 19 = = 0 : print (y, "Is Even Number" ) else : print (y, "Is Odd Number" ) |
24 Is Even Number 19 Is Even Number
Time Complexity : O(1)
Auxiliary Space : O(1)
Check Even or Odd Numbers using recursion in Python
We use the concept of getting the remainder without using the modulus operator by subtracting the number by 2. In the below code, we are calling the recursion function by subtracting the number by 2. In the base condition, we are checking whether the n becomes equal to 1 or 0. If n==1 it is odd and if n==0 number is even.
Python3
# defining the function having the one parameter as input def evenOdd(n): # if remainder is 0 then num is even if (n = = 0 ): return True # if remainder is 1 then num is odd elif (n = = 1 ): return False else : return evenOdd(n - 2 ) num = 33 if (evenOdd(num)): print (num, "num is even" ) else : print (num, "num is odd" ) |
33 num is odd
Time Complexity: O(n/2)
Auxiliary Space: O(1)
Check Even or Odd Numbers using & operator in Python
If we observe the binary representation of a number we will know that the rightmost bit of every odd number is 1 for even numbers it is 0. Bitwise AND (&) operator gives 1 only for (1&1) otherwise it gives 0. So, knowing this we are going to evaluate the bitwise AND of a number with 1 and if the result is 1 number is odd, and if it is 0 number is even. For example, 5 & 1 are evaluated as given below.
1 0 1 - 5
& 0 0 1 - 1
-----
0 0 1 - 1
-----
Python3
# defining the function having # the one parameter as input def evenOdd(n): # if n&1 == 0, then num is even if n & 1 : return False # if n&1 == 1, then num is odd else : return True # Input by Lazyroar num = 3 if (evenOdd(num)): print (num, "num is even" ) else : print (num, "num is odd" ) |
3 num is odd
Time Complexity : O(1)
Auxiliary Space : O(1)