How to add two long integers in Python 3? || Python Addition Manually.

Hi Guys, In this tutorial, I am going to show you how to add two big integers in python 3.

With the default addition system of python, you can not add two Long integers. To add two big integers, You need to go through string addition process.  Each Corresponding character of two strings are converted into integer & are added them & the sum,carry are stored in two variables.

If one number( one strings or List in this case) has less length than other, then that list is labeled with required zero(s) {0 } and are added .

 The implementation in Python 3 is:

x=input()
y=input()
def zeroMaking(x,y):
    zero=''
    for i in range(max(len(x),len(y))-min(len(x),len(y))):
        zero=zero+'0'
    return zero

def swapAndAdjustment(x,y):
    zero=''
    zero=zeroMaking(x,y)
    if len(y)>len(x):
        tmp=y
        y=x
        x=tmp
        zero=y+zero
        y=zero
    if len(y)<len(x):
        #tmp=y
        #y=x
        #x=tmp
        zero=y+zero
        y=zero
    return x,y
    
    
def addition(x,y):
    x=x[::-1]
    y=y[::-1]
    z=[];c=0;
    #zero=zero(x,y)
    x,y=swapAndAdjustment(x,y)
    #print(x,"   ",y)
    for i,j in zip(x,y):
        add=int(i)+int(j)+c
        if (add)>=10:
            z.append(add-10)
            c=1
            last=1
        else:
            c=0
            z.append(add)
            last=0
    if last==1:
        z.append("1")
    print(*z[::-1])

addition(x,y)

ZeroMaking Function  makes the  required amount of zero(s) . Here, Absolute(Length of Number1 - Length of Number2) amount of zero are produced & stored in a Python list. if the first number is : 67554 & the second  number is: 45, then (5-2)==3 zeros will be produced.


Here, SwapAndAdjustment function adjust two numbers  as if they are of same length adding at the first  with required  zeros if needed.

Finally, The addition function adds two numbers & return the output.


You can use the above code anywhere  you need. If you have any problem in understanding the code above, Feel free to comment below.
Writer: Md. Rahat
Computer Science & Engineering Department,
University of Barisal





Comments