Write a program that performs the addition of two numbers that are expressed in any arbitrary base.
To compute the sum of two numbers, we compute the sum of each pair of digits, starting with the least significant ones, and the carry-over from the sum of the previous pair of digits.
In order to perform this operation in a program, we have to break our algorithm into three parts:
Example 1:
Compute the sum of the two base-10 numbers 6592 and 7685Part1:
Part 2:
Digit 1 Digit 2 6592 % 10 => 2 7685 % 10 => 5 (6592 / 10) % 10 => 9 (7685 / 10) % 10 => 8 (6592 / 100) % 10 => 5 (7685 / 100) % 10 => 6 6592 / 1000 => 6 7685 / 1000 => 7 Part 3:
Carry Over
(from previous line)Digit 1 Digit 2 Sum Result Digit Carry Over
(to next line)0 2 5 7 7 % 10 = 7 7 / 10 = 0 0 9 8 17 17 % 10 = 7 17 / 10 = 1 1 5 6 12 12 % 10 = 2 12 / 10 = 1 1 6 7 14 14 % 10 = 4 14 / 10 = 1 Result : 7 + 7 * 10 + 2 * 100 + 4 * 1000 + 1 * 10000 = 14277Note: The final term in the addition is the final carry over.
Example 2:
Compute the sum of the two base-8 numbers 6512 and 675Part1:
Part 2:
Digit 1 Digit 2 6512 % 10 => 2 675 % 10 => 5 (6512 / 10) % 10 => 1 (675 / 10) % 10 => 7 (6512 / 100) % 10 => 5 (675 / 100) % 10 => 6 6512 / 1000 => 6 675 / 1000 => 0 Part 3:
Carry Over
(from previous line)Digit 1 Digit 2 Sum Result Digit Carry Over
(to next line)0 2 5 7 7 % 8 = 7 7 / 8 = 0 0 1 7 8 8 % 8 = 0 8 / 8 = 1 1 5 6 12 12 % 8 = 4 12 / 8 = 1 1 6 0 7 7 % 8 = 7 7 / 8 = 0 Result : 7 + 0 * 10 + 4 * 100 + 7 * 1000 + 0 * 10000 = 7407Note: The final term in the addition is the final carry over.
The program you have to write will read a base and two numbers of at most 4 digits in that base. The program will compute the sum of the two numbers using the above algorithm and display the result.
Example run:
Enter base: 8 Enter two numbers (no more than 4 digits) in base 8: 2361 6642 Result: 2361 + 6642 = 11223Notes:
- You should run the program at least twice with different bases.
- You can assume all inputs are correct (numbers expressed in the right base, etc.)