Arithmetic
One of the drawbacks of the standard representation of Integers on a
computer is the limited storage of a fixed size value. On some
occasions you just need to be able to work with larger numbers. On a
PC, the largest numbers that can be easily worked with are in the
billions, about 10e9. In this assignment you will develop a method
for performing some simple arithmetic on numbers much, much, larger.
Specs
You already know the algorithm for adding numbers (add the ones
column, carry if needed, add the 10s column, etc). You've been doing
it for many years. In this assignment, the difficulty will only be
translating that algorithm into code.
Your task is to implement functions add & multiply. Since
the int type has limited capacity, you will instead be
representing numbers in type string. To make this as simple as
possible, only one function needs to have any major complexity:
add. If you have add written, multiply is simply a
matter of a while loop calling add. Since add is
such an important thing, it is very important that you think
ahead. Do not be afraid to start over if you are getting
confused.
Your main program will be a simple 2 function calculator: read in a
string (which you may assume represents an arbitrarily long integer),
followed by an operator (either '+' or '*'), and another long
integer, and then print out the results of the operation as
appropriate.
A binary sample of the program can be found here.
To run it, save it to your Linux account, run the command "chmod +x
arith", and then execute as normal.
Turn in your program as "arith.cc"
Hints
- One of the largest difficulties with a string representation is the
fact that the ones place (which we would normally think of as num[0])
is going to be at the end of the string (num[num.size() - 1]).
- Remember to carry the one!
- If your two numbers are not the same length, add '0's to the
smaller one to make it the same length, this will make things easier.
- Think about which end of the string you can add '0's to!
- Remember to carry the one on the last digit. The return value
will be either the same size as the longest string, or one digit
longer.
- Multiplication will require you to add a to itself b
times or vice-versa. Since a and b are not ints, you
can't just use a for loop. How will you implement a loop that works
the correct number of times?
- Note: Multiply implemented this way will probably take a
long time (several seconds) to perform complicated operations. If you
think there is a problem, try using the debugger, but don't despair:
this is not an efficient method of implementing the multiplication
operation.