Learn Math With Python

3. Learn Math With Python – Divisibility of Numbers

For two given numbers a and b (a > 0), a is said to be divisible by b, if b completely divides b (without leaving any remainder). For example 18 is divisible by 3.

% operator is used to find a remainder when one number is divided by another number.

3.1 Use of % Operator

For example a % b means remainder when a is divided by b.

#Accepting values
num = int (input ('Enter the number whose divisibility needs to be checked: '))
div = int (input ('Enter the number with which divisibility needs to be checked: '))

#Checking divisibility
if num % div == 0:
print (num, 'is divisible by ', div)
else:
print (num, 'is NOT divisible by ', div)

3.2 Checking For Even or Odd Number

A number is called an even number if it is divisible by 2 and is called an odd number if it is not divisible by 2. For this, you’ll divide a number by 2 and find the remainder (using modulus operator %). If the remainder is 0, then the number is even, otherwise the number is odd.

Note: The remainder when a  number is divided by 2 is always one of the following:

  • 0 – Divisible
  • 1 – Not divisible
#Accepting number
num = int (input ('Enter a number: '))

#Checking for Even or Odd
if num % 2 == 0:
print (num, 'is Even ')
else:
print (num, 'is Odd ')

3.3 Counting Even & Odd Numbers

import array as arr
numbers = arr.array('i', [])
num = input("How many numbers do you want to enter? ") #user tells the range(optional)

#iterating till user's range is reached
for i in range(int(num)): 
    n = input("Enter a value ")#asking for input of 1 value 
    numbers.append(int(n))#adding that value to the array

even = 0
odd = 0
#iterating till user's range is reached
for i in range(int(num)): 
  if numbers[i]%2 == 0:
  		even += 1
  else:
		  odd += 1

print("Number of Even Numbers = ", even)
print("Number of Odd Numbers = ", odd)

Leave a Comment