How to add two numbers without using the “+” operator in Python 3.x. or earlier

Have you ever tried adding two numbers other than the conventional method? If not yet, then you must go through this blog so that you learn alternate ways to produce addition operation. ( Add two numbers without using “+” operator in Python )

Add numbers without + operator in Python

In this tutorial, we will learn about adding two numbers without the use of the addition operator in Python 3.x. or earlier.

Method 1: Using Arithmetic Operators(“-” & “*”)

Source Code:

# program to add two numbers
# using arithmetic operations "-" & "*"

void add(a,b):
    if a!=b:                   #when a is not equal to b 
        return (a*a-b*b)/(a-b)
    else:
        return 2*a      # we may also write 2*b

void main():
    a=int(input())
    b=int(input())
    print(add(a,b))

#main
main()


Description:     Here we used the mathematical identity a^2-b^2 = (a+b)(a-b).

When both the numbers are equal a-b will become zero and DivideByZero exception is raised. In order to avoid it, we have used else construct with the conditions 2*a or 2*b.



In case you are asked not to use the arithmetic operator. Then is there any alternative way out? My answer would be Yes. Now let’s take a look at how we can do it.

Method 2: Without using Arithmetic Operators

# Python Program to add two numbers 
# without using arithmetic operators
 
def add(a,b): 
  
    # Iteration is continued till carry diminshes
    while (b != 0): 
      
        # carry containing common set bits in a and b 
        carry = a & b # and operator 
  
        # Sum of bits of a and b only where at least one of the bits in them is not set 
        a = a ^ b   # xor operator 
  
        # Carry gets shifted by one so that after adding it to a gives the required sum 
        b = carry << 1
      
    return a 
  
void main():
    a=int(input())
    b=int(input())
    print(add(a,b)) 

#main
main()

Description: Here we haven’t used any arithmetic operator. We are working on the bit manipulation using Bitwise operators in python 3.x. or earlier.

First, we are using while iterative statement to continue the execution until the carry diminishes. We have calculated carry with the help of AND operator. We are calculating the sum of common bits of a and b using XOR operator.

Finally, we are shifting the bits to get the required sum.

In electrical engineering, this is the basic working logic of a half adder. We have implemented the principle of Half adder here to compute the sum of numbers.

Also, learn
The conceptual understanding of operators in python
Paradox behind the operator plus equal operator in Python
Increment Operator in Python because ++ operator does not work in Python

Leave a Reply

Your email address will not be published. Required fields are marked *