c++clogicadditionnumber-systems

Add two octal numbers directly without converting to decimal


I'm trying to add two octal numbers by adding the corresponding digits but, I'm stuck when the case is that the sum of digits is greater than 7. I'll have to take a carry and add it to the next addition cycle. I'm unable to find the right expression to consider the carry and compute the final sum.

Another case to consider is when the octal numbers a and b do not have same number of digits, ex: 6 and 13 (6+13=21 in octal). I'm unable to establish a condition for the while loop for such a condition (if both have same number of digits I can run the while loop till either of them or both of them become zero)

Can somebody please help/complete the following code:

int octal_sum(int a,int b)     //a and b and octal numbers
{
    int sum=0,carry=0,d=0;
    while(**???**)
    {
        d=0;
        d=carry+(a%10)+(b%10);
        a/=10;b/=10;
        if(d>7)
        {
            carry=1;
            d=d%8;
        }
        sum= **???**
    }
   return sum;     //returns octal sum of a and b
}

Solution

  • Here is the function I made. It is important to remember about the carry. Because if your numbers add up to be longer (ex: 7777 + 14 = 10013) if you ignore the carry, the code will only return four digits (your longest lenght of number), so 0013, which is 13. Not good. So we need to account for the carry. We must continue our loop until both our numbers and the carry are all 0.

    Further more, if the digit you obtain by calculating a%10 + b%10 + carry is smaller than 8, then we no longer need to carry again, so we need to reset the value.

    Note I'm using a digit rank integer, which basically allows me to add the digit to the beginning of the sum by multiplying by powers of ten and then adding it to the sum.

    The final code looks like this.

    int octal_sum(int a, int b)
    {
        int sum = 0, digit = 0, carry = 0, digit_rank = 1;
    
        // Calculate the sum
        while (a > 0 || b > 0 || carry)
        {
            // Calculate the digit
            digit = a % 10 + b % 10 + carry;
    
            // Determine if you should carry or not
            if (digit > 7)
            {
                carry = 1;
                digit %= 8;
            }
            else
                carry = 0;
    
            // Add the digit at the beggining of the sum
            sum += digit * digit_rank;
            digit_rank *= 10;
    
            // Get rid of the digits of a and b we used
            a /= 10;
            b /= 10;
        }
        return sum;
    }
    

    Hope it helped you!