Amazon Interview Question
Software DevelopersCountry: United States
Interview Type: In-Person
we can store very large numbers by using string and make calculations by defining the operations in string.
Example:
function cmp(a,b : bigNum): integer;
begin
while length(a)<length(b) do a:='0'+a;
while length(b)<length(a) do b:='0'+b;
if a = b then exit(0);
if a > b then exit(1);
exit(-1);
end;
a number can be a real, ration, integer or natural number:
- Chris July 04, 2017let's assume we want at least integers:
- a decimal representation (is slower, has little advantage, maybe printing is easier). Here we use typically 4 bits per decimal.
- a binary representation where you use a sequence of machine word that is dynamically grown if more space is needed (the number gets bigger)
- in any case, you need a bit/flag for the sign
With rational numbers, that's just having a nominator and denominator of type integer and you get along with high-school math for all operations, maybe need to look up gcd algorithm.
real numbers grow in size and precision if you apply division. I'm not fit enough in number theory to answer how you need to implement the division so you can keep the precision. For the first division it's relatively simple, because you can easily identify the repeating sequence. But for example if you start calculating PI from a very long series ...?
how is addition done: basically how we learned it in high school decimal by decimal carrying an overflow consider signs. subtraction is very similar. How ever, with binary representation, instead of a decimal place use the machine word and the add / sub on the ALU of CPU which is faster than shifting around manually.
Multiplication is similar, early high-school method as is division. But both division and multiplication have more effective algorithms reducing the amount of machine-word multiplications/divisions dramatically. Multiplication is realtively easy to understand whereas division is more complex using FFT.
MIT OCW 6.006, Lecture 11 found on [http]ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-11-integer-arithmetic-karatsuba-multiplication/ has some good first steps into the topic