Search code examples
c++arrayssubtraction

How do i subtract equal digit large numbers?


I have subtracted large numbers whose digits are unequal in length but I cant subtract numbers which are equal in length.I am taking a 2 string as input from the user which are numbers and I am converting it into integer array using str[i]-'0'.Till now I have swapped values of smaller length - bigger length integers.I have to do subtraction for 50 digit numbers.I can do subtraction of unequal length strings.But, in case of equal length numbers I am unable to do that.I cant use atoi function.What I have done is converted string to integer array and then I am doing subtraction using subtraction logic in sub_logic HEre is my logic for subtraction of equal digit numbers.


Solution

  • Semi-answer because I can't think of a good reason to debug Asker's algorithm when a much simpler approach is viable.

    This is your great opportunity to act like a child.

    1. Leave the numbers as strings1.
    2. Make them both the same size by prepending zeros to the shortest.
    3. If the number being subtracted (the subtrahend) is the larger number, reverse the two numbers so you are always subtracting the smaller number from the larger. Make a note that you reversed the order of the operands.
    4. Working right to left, subtract the digits and track any borrowing from the larger digits as required.
    5. If you reversed the operand order, mark the result as negative.

    1You do not have to parse the characters into numbers because no sane character encoding scrambles the ordering or positioning of the numbers. The C++ standard [lex.charset] requires this.

    However, tracking borrowing may force you to use a wider storage this as you may find yourself with a number as high as 18 which the C++ standard does not guarantee a character can store. Overshooting what you can store in a digit and counting on another character to be there will not work if the numbers are at the end of the encoding. This is not a problem with every character encoding I know of, but not guaranteed.

    You can most likely (assuming ASCII here) get away with

    if (a[index] < b[index]) 
    {
        a[index - 1]--; // a > b as per step 3 above, so this can't happen with last digit.
        a[index] += 10;
    }
    result[index] = '0' + a[index] - b[index];
    

    for step 4. I believe this to be a good assumption for a school assignment, but I'd be more careful with production code to make sure a[index] += 10; won't overflow a char

    The borrowed numbers will wind up sitting on top of ';' through 'a' and no one will care in terms of the math. It's destructive though. a is damaged as a result