Thanks to visit codestin.com
Credit goes to tutorialwing.com

Python Program to Add two Numbers without using Addition Operator

In this article, we will learn about python program to add two numbers without using addition operator (i.e. + operator)

Getting Started

The task is use to add two numbers in python without using + operator.

In other words,

We have to add two numbers a and b without using + operator.

Add Two Numbers in Python Without + operator

We will be using Half Adder Logic to add two numbers.

Pseudo Algorithm using Half Adder Logic

  • Let’s say we want to add two numbers a and b.
  • Step 1: If both numbers don’t have set bit (i.e. 1) at same position, simply XOR operation (^) gives sum of a and b.
  • Step 2: Else if they have set bits at same position, AND operation (bitwise &) provides carry bits at all position.
  • Step 3: Now, left shift carry bits by 1 and add it to result obtained it by performing XOR operation.
  • Step 4: Repeat step 1, step 2 and step 3 until carry is zero (i.e. 0).

Python Program

 
def addWithoutOperator(a, b):

    # Run while carry is not 0
    while (b != 0):
        
        # Carry contains common set bits of a and b
        carry = a & b
        
        ## partial sum where a^b contains sets bits either from a or b.
        a = a ^ b

        # Shifts the carry by 1 bit so that it gives required sum when added with a in next iteration.
        b = carry << 1
    return a


print("Sum = ", addWithoutOperator(15, 31))

Output:

 
Sum =  46

Python Program to Add Two Numbers Using Recursion

We can write above program using recursion to add two numbers in python as shown below –

 
def addWithoutOperator(a, b):
    if (b == 0):
        return a
    else:
        return addWithoutOperator( a ^ b, (a & b) << 1)
        
print("Sum = ", addWithoutOperator(15, 31)) 

Output:

 
Sum =  46

In above program, calling addWithoutOperator method until carry is 0.

Time complexity: O(log b)

Space complexity: O(1)

That’s how we can write python program to add two numbers without using addition operator.

Learn more python programs at – https://tutorialwing.com/python-tutorial/

Leave a Reply