Python program to implement Half Adder
Prerequisite: Half Adder in Digital Logic
Given two inputs of Half Adder A, B. The task is to implement the Half Adder circuit and Print output i.e sum and carry of two inputs.
Half Adder: A half adder is a type of adder, an electronic circuit that performs the addition of numbers. The half adder is able to add two single binary digits and provide the output plus a carrying value. It has two inputs, called A and B, and two outputs S (sum) and C (carry).
Logical Expression:
Sum = A XOR B
Carry = A AND B
Truth Table:
Examples:
Input : 0 1
Output: Sum=1, Carry=0
Explanation: According to logical expression Sum=A XOR B i.e 0 XOR 1 =1 , Carry=A AND B i.e 0 AND 1 =0
Input : 1 1
Output: Sum=0, Carry=1
Explanation: According to logical expression Sum=A XOR B i.e 1 XOR 1 =0 , Carry=A AND B i.e 1 AND 1 =1
Approach:
- We take two inputs A and B.
- XOR operation on A and B gives the value of the sum.
- AND operation on A and B gives the value of Carry.
Below is the implementation.
Python3
def getResult(A, B):
Sum = A ^ B
Carry = A & B
print ( "Sum " , Sum )
print ( "Carry" , Carry)
A = 0
B = 1
getResult(A, B)
|
Output:
Sum 1
Carry 0
Method#2:Using numpy:
Algorithm:
- Import the required NumPy library.
- Define the function half_adder(A, B) which takes two input bits A and B as arguments.
- Calculate the Sum of the two input bits using the NumPy bitwise_xor() function which returns the bitwise XOR of two input arrays.
- Calculate the Carry of the two input bits using the NumPy bitwise_and() function which returns the bitwise AND of two input arrays.
- Return the calculated Sum and Carry values.
- Define the input bits A and B.
- Call the half_adder() function with the input bits A and B and store the returned Sum and Carry values.
- Print the calculated Sum and Carry values.
Python3
import numpy as np
def half_adder(A, B):
Sum = np.bitwise_xor(A, B)
Carry = np.bitwise_and(A, B)
return Sum , Carry
A = 0
B = 1
Sum , Carry = half_adder(A, B)
print ( "Sum:" , Sum )
print ( "Carry:" , Carry)
|
Output:
Sum: 1
Carry: 0
Time complexity:
The time complexity of this code is O(1) since the calculations involved in the half_adder() function take constant time regardless of the input values.
Auxiliary Space:
The space complexity of this code is O(1) since the function only uses a constant amount of memory to store the input variables, intermediate variables, and output variables.
Last Updated :
25 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...