Multiplication of Two Integers

Let's take a look into how to multiply two integers with n number of digits. (say x and y)

We partition the two numbers as,      x = 10^(n/2) a  +  b        and      y  = 10^(n/2) c  +  d

Then,  x . y  =  [10^(n/2) a  +  b] . [10^(n/2) c  +  d]
           x . y  =  10^(n) ac  +  10^(n/2)  (ad + bc)  +  bd

The idea behind this is to form a recursive function that simply halves the number we multiply each time and pass in a number that has less digits than the original number.

In this case, we recursively calculate  ac , ad,  bc,  bd   and finally get the result.
Our base case would be when the number of digits of the numbers to be multiplied is 1.

But we can do better than this using the idea of found by Gauss..

Karatsuba Multiplication

x . y  =  10^(n) ac  +  10^(n/2)  (ad + bc)  +  bd

The trick was instead of using four recursive calls on:   ac , ad,  bc,  bd ,  we just use three recursive calls on:   ac , (ad +  bc),  bd

First step is to calculate      : ac.
Second step is to calculate : bd.
Third step is to calculate     : (a + b) (c + d) = ac + bd + ad + bc

So by subtracting the first two steps from the third step, we end up with (ad + bc) which we are really interested in.

Therefore this reduces the recursive calls to three. Hence improving the run time of the algorithm.
SHARE

Milan Tomic

Hi. I’m Designer of Blog Magic. I’m CEO/Founder of ThemeXpose. I’m Creative Art Director, Web Designer, UI/UX Designer, Interaction Designer, Industrial Designer, Web Developer, Business Enthusiast, StartUp Enthusiast, Speaker, Writer and Photographer. Inspired to make things looks better.

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment