Multiplying Large Numbers with Karatsuba`s Algorithm
Numbers are magic; magic by their properties, their existence, and most importantly, their huge impact on our day-to-day modern life. Everything can be reduced and narrowed down to numbers. In this second part of our series on large numbers, we'll delve more deeply into this magic.
Multiplying Large Numbers with Karatsuba`s Algorithm - Apply What We Have Just Learned (Page 4 of 4 )
As we passed through the previous pages we learned all that we are going to need in order to produce the desired result. Because we have real numbers and not only integers we'll resolve this problem by calling Karatsuba's algorithm for the two numbers and calculate the place of the comma in the result after finishing the operation. We simply have to add the real length of the two numbers. This is realized by the following line.
Brief explanation: If we're in the range simply calculate the result with the Classic method. Otherwise, find the middle, divide the numbers, calculate the sum of the elements, call Karatsuba's algorithm to calculate the multiplications, shift the items, and add the items. Return the result.
Now all we need to do is check out the results! For some obvious reasons now I won't venture to multiply two numbers that are 10 MB because it would take an awfully long time on my decent system (AMD Sempron 3000+ with default clocks and 1 GB DDR400 memory with a Western Digital 200 GB ATA133 Hard Disk). But look first for two 10K numbers and after it two 100K numbers.
And a little longer for the 100K numbers:
As you can see multiplication is a bit more complex than addition and takes much more time to complete. Also here is as promised the source code with the class implementation, so you can skim through it freely and see how it works with a debugger eventually. The project that is included is created with Visual Studio 2005 so with earlier versions you can't open it, but if you create a new solution it should work.
I hope you have enjoyed this session too. I wish you a nice day and all the best until the upcoming next part in which we'll try to solve the divide operation. If you have some additional question related to this part or even the previous one or observations about it, you shouldn't hesitate to visit our friendly ever-growing forum at the Dev Hardware.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.