-1

CLRS is the book Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein.

Problem:

Consider the problem of adding two n-bit binary integers, stored in two n element arrays A and B. The sum of the two integers should be stored in binary form in an (n + 1) element array C.

Why is carry needed in the correct solution?

My solution:

def AddBinary(A,B):
    n = max(len(A),len(B))
    C = [0 for i in range(n+1)]
    for i in range(n):
        C[i] = (A[i] + B[i]) % 2
    return C

correct solution:

def AddBinary(A,B):
    carry = 0 
    n = max(len(A),len(B))
    C = [0 for i in range(n+1)]
    for i in range(n):
        C[i] = (A[i] + B[i]+carry) % 2
        carry = (A[i] + B[i]+carry) // 2
    C[n] = carry
    return C
martineau
  • 119,623
  • 25
  • 170
  • 301
Memory1
  • 67
  • 1
  • 1
  • 8
  • 1
    Because the carry is needed when you're adding to numbers together digit-by-digit to get the correct answer — just like how you were (presumably) taught in elementary school. – martineau Feb 12 '22 at 18:17
  • Do you also think that 23+18 is 31? – Kelly Bundy Feb 12 '22 at 18:18
  • @Pumpkin Wow thanks, you are a great example of why this site is awesome. You must be great to work with. – Memory1 Feb 12 '22 at 18:33

1 Answers1

0

You're asking about the basic nature of performing addition place by place in whatever base. If you can recall how we were taught decimal (base 10) addition early on, we were told to carry the "overflow" to the next digit, right? The code needs to do the same thing. The carry is a critical part of the operation.

Here's a simple way to see this. Consider adding two 2-digit binary numbers:

01 + 01 = 10   # (1 + 1) % 2 == 0 + carry, (0 + 0 + carry) % 2 == 1

or in decimal, 1 + 1 = 2. Now apply your logic that ignores the carry:

01 + 01 = 00   # (1 + 1) % 2 == 0, (0 + 0) % 2 == 0

so here, 1 + 1 = 0. That clearly isn't correct. In this trivial example, the carry produces the entirety of the resulting value.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44