-1

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
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Abhilash Kishore
  • 2,063
  • 2
  • 15
  • 31
  • 3
    You could do `a + b` and use `std::oct` for input/output, but that would be too simple. There isn't any difference between octal/decimal/hexadecimal `int`. It's always binary, it's the way you read/print it. – LogicStuff Dec 18 '15 at 19:51
  • How do you represent "octal" numbers? – Karoly Horvath Dec 18 '15 at 19:56
  • @Abhilash Making `int` represent an octal value after printed out as decimal is just madness. – LogicStuff Dec 18 '15 at 19:57
  • 1
    The arguments `int a, int b` are not octal numbers unless you have an unusual computer. Octal is a text format. – Weather Vane Dec 18 '15 at 20:03
  • 1
    LogicStuff and @WeatherVane int a,b are not octal numbers by data type, agreed, but I have octal numbers stored in them (doesn't have 8 & 9 though it _can_ have) and I'm making sure that I pass purely octal numbers as parameter – Abhilash Kishore Dec 18 '15 at 20:07
  • It doesn't make sense. What are you passing in? You can do I/O with `std::oct` and have number literals with `0` prefix. What you're doing now, you could as well do with `std::string`. – LogicStuff Dec 18 '15 at 20:10
  • 1
    @Abhilashk you accepted that good answer, but your second question refers to the octal values having *different number of digits*. I suggest you would be better off working with digit array arithmetic. Find out which array is shorter. Add the two arrays, and use the final carry to continue the sum from the longer array. – Weather Vane Dec 18 '15 at 20:15

4 Answers4

3

Since you are passing ints, I assume that you are using decimal-coded octals*, i.e. decimal numbers that use only digits 0 through 7, inclusive. For example, number 1238 which is actually 8310 would be coded as 12310 using your scheme.

  • Deciding on the stopping condition - you want your while loop to continue until both numbers a, b, and carry turn zero. In other words, the condition should be a || b || carry
  • Adding the next digit to the sum - since the result is coded as decimal, you need to multiply digit d by the next consecutive power of ten. A simple way of doing that would be adding a new variable m which starts at 1 and gets multiplied by ten each iteration.

The result would look like this:

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

Demo.

* This would be similar to Binary-Coded Decimal (BCD) representation, when a representation capable of storing hex digits is used to store decimal digits.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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!

Jadarma
  • 160
  • 1
  • 1
  • 13
0

I wrote it as simpler as possible

#include<iostream>
#include<cmath>
using namespace std;

int sum(int x, int y)
{
    int r1, r2;
    int sum = 0;
    int carry = 0;
    int i = 0;
    

    while (x != 0 || y != 0)
    {
        r1 = x % 10;
        r2 = y % 10;
        int s = r1 + r2 + carry;
        if (s < 8)
        {
            sum = sum + (s * pow(10, i));
            carry = 0;
        }
        
        else
        {
            // Do write s%8 rather writing (r1+r2+carry-8)
            sum = sum + (s%8 * pow(10, i));
            carry = 1;
        }
        x = x / 10;
        y = y / 10;
        i++;
        
    }
    if (carry == 1)
    {
        sum = sum + (1 * pow(10, i));
    }
    return sum;
}
int main()
{
    int x, y;
    cout << "Enter two numbers:\n";
    cin >> x >> y;
    cout << sum(x, y);
}
-1
  1. I am using StringBuilder to append character, which is better than using Strings, it's immutable.

2.read the char from String by converting String to char array, converting char to an integer by subtracting from its ASCII value '0'

  1. make sure handle the carryforward case too
private static String OctaNumberAddition(String o1, String o2) {
    StringBuilder sb = new StringBuilder();
    int carry = 0;
    for(int i = o1.length() - 1, j =o2.length()-1;i >= 0 || j >= 0;i--,j--){
        int sum = carry + (i >= 0 ? o1.charAt(i) - '0':0)+(j >= 0 ? o2.charAt(j) - '0':0);
        sb.insert(0,sum%8);
        carry = sum /8;
    }

    if(carry > 0){
        sb.insert(0,carry);
    }

    return sb.toString();
}