Python Program to Multiply Two Binary Numbers
Last Updated :
23 Feb, 2023
Given two binary numbers, and the task is to write a Python program to multiply both numbers.
Example:
firstnumber = 110
secondnumber = 10
Multiplication Result = 1100
We can multiply two binary numbers in two ways using python, and these are:
- Using bin() functions and
- Without using pre-defined functions
Method 1: Using bin Functions
Now, Let’s write a program by using Pre-Defined Functions:
Python3
firstnumber = 110
secondnumber = 10
firstnumber = str (firstnumber)
secondnumber = str (secondnumber)
Multiplication = int (firstnumber, 2 ) * int (secondnumber, 2 )
binaryMul = bin (Multiplication)
print ( "\nResult = " + binaryMul)
|
Output:
Result = 0b1100
Time complexity: O(1)
Auxiliary space: O(1)
Method 2: Without using Any Pre-Defined Function
We can also multiply any two Binary Numbers without using any pre-defined Function or by user-defined function.
Python
def binaryProduct(binaryOne, binaryTwo):
i = 0
remainder = 0
sum = []
binaryProd = 0
while binaryOne ! = 0 or binaryTwo ! = 0 :
sum .insert(i, (((binaryOne % 10 ) + (binaryTwo % 10 ) + remainder) % 2 ))
remainder = int (((binaryOne % 10 ) + (binaryTwo % 10 ) + remainder) / 2 )
binaryOne = int (binaryOne / 10 )
binaryTwo = int (binaryTwo / 10 )
i = i + 1
if remainder ! = 0 :
sum .insert(i, remainder)
i = i + 1
i = i - 1
while i > = 0 :
binaryProd = (binaryProd * 10 ) + sum [i]
i = i - 1
return binaryProd
binaryMultiply = 0
factor = 1
firstBinary = 110
secondBinary = 10
while secondBinary ! = 0 :
digit = secondBinary % 10
if digit = = 1 :
firstBinary = firstBinary * factor
binaryMultiply = binaryProduct(firstBinary, binaryMultiply)
else :
firstBinary = firstBinary * factor
secondBinary = int (secondBinary / 10 )
factor = 10
print ( "\nMultiplication Result = " + str (binaryMultiply))
|
Output:
Multiplication Result = 1100
Time complexity: O(n), where n is the length of the binary numbers.
Auxiliary space: O(n), as we are storing the binary product in the sum array.
Python3
from operator import *
num1 = "110"
num2 = "10"
print ( bin (mul( int (num1, 2 ), int (num2, 2 ))))
|
Output
0b1100
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...