Question

(Python) A large integer can be implemented by an array or a list. Write a function...

(Python) A large integer can be implemented by an array or a list. Write a function that does the addition of two large integers.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

# Function for finding sum of larger numbers
def findSum(str1, str2):

   # Before proceeding further, make sure length
   # of str2 is larger.
   if len(str1)> len(str2):
       temp = str1
       str1 = str2
       str2 = temp

   # Take an empty string for storing result
   str3 = ""

   # Calculate length of both string
   n1 = len(str1)
   n2 = len(str2)
   diff = n2 - n1

   # Initialy take carry zero
   carry = 0

   # Traverse from end of both strings
   for i in range(n1-1,-1,-1):
  
       # compute sum of
       # current digits and carry
      
       sum = ((ord(str1[i])-ord('0')) +
               int((ord(str2[i+diff])-ord('0'))) + carry)
  
       str3 = str3+str(sum%10 )
      
      
       carry = sum//10

   # Add remaining digits of str2[]
   for i in range(n2-n1-1,-1,-1):
  
       sum = ((ord(str2[i])-ord('0'))+carry)
       str3 = str3+str(sum%10 )
       carry = sum//10

   # Add remaining carry
   if (carry):
       str3+str(carry+'0')

   # reverse resultant string
   str3 = str3[::-1]

   return str3


if __name__ == "__main__":
   str1 = input("First number: ")
   str2 = input("second number: ")
   print("sum of two numbers:",findSum(str1, str2))


ch py- C/Users/Tarun/Documents/ch.py (8.7.2) File Edit Format Run Options Window Help # Function for finding sum of larger nuch py- C/Users/Tarun/Documents/ch.py (8.7.2) File Edit Format Run Options Window Help # initialy take carry zero carry = 0 #OUPUT:

ech.py - C:/Users/Tarun/Documents/ch.py B.7.2) Python 3.72 Shell File Edit Shell Debug Options Window Help Python 3.7.2 (tags

Add a comment
Know the answer?
Add Answer to:
(Python) A large integer can be implemented by an array or a list. Write a function...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT