Python program to check a binary number is divisible by a number N.
In this tutorial, we will see how to check a binary number is divisible by a number N in Python programming. The value of the variable N and binary number is provided by the user. To solve this, we will also learn how to convert to binary numbers to decimal numbers. Before going to solve this problem, we will learn a little bit about the binary number.
What is the binary number?
A binary number is a number which expressed in the base 2 numeral system which uses only two symbols 0 and 1.
Before going to solve the above mention problem, we will go to write Python code that converts binary to decimal in a simple way.
b=100101 n=int(str(b),2) print(n)
Here, we have assumed a binary number 100101 which is a binary form of 37.
Python program to check a binary number is divisible by a number N
Let us assume the binary number and value of n provided from the user are 11001110001 and 3 respectively. We all know that the divisibility condition of 3, a number is divisible by 3 if the sum of digits of the number is also divisible by 3. As we have learned to convert binary to decimal number. Here, we simply divide the decimal number by 3 if there is no remainder then it is divisible by 3.
b=110011001 n=3 a=int(str(b),2) if a%3==0: print('Divisible by 3') else: print('Not divisible by 3')
Not divisible by 3
For other values of N, you can add the perfect logic. Like a number will be divisible by 5 if the last digit of the number is 5 or 0.
So Guy’s, I hope you find it useful.