Skip to main content

Fast Multiplication of Long Integeres | Karatsuba's Algorithm


This article is divided into 3 parts, so feel free to skip around to the part you find useful -

Need for the algorithm

Multiplication is an elementary concept known to all of us since a very early age. But multiplication of very large numbers becomes a difficult problem that can't be solved mentally unless you're a mathematical genius and hence we use calculators and computers.
Computers too can efficiently multiply numbers but as the length of digits of the number increases, the time complexity also increases along with it quadratically.
To calculate the product of humongous numbers we need a better algorithm. Any algorithm that even slightly increases the runtime will prove to be very beneficial for large values of n, say 100000. Karatsuba multiplication algorithm brings down the number of operations by a factor of one and gives a huge boost.

Intuition and Algorithm

Okay so, to boost up the speed of multiplication we can use the distributive law.
Split the numbers into two parts and then multiply them. To demonstrate this we will take an example,
To multiply two numbers, u = 82 and v = 73, we can divide them both in the following way -
u = 8 * 10 + 2
v = 7 * 10 + 3
We can see a general form -
u = x * 10 + y
v = w * 10 + z
u * v = (x * 10 + y) * (w * 10 + z)
u * v = xw * 102 + xz * 10 + yw * 10 + yz
Now if we plug in the values,
82 * 73 = (8*7) * 100 + (8*3) * 10 + (2*7) * 10 + (2*3)
This will give us the result 5986.
This algorithm involves 4 basic multiplication operation. We can ignore anything multiplied by 10 to the power something as it is just a matter of appending 0s. This approach still gives us a time complexity of O(n2) which is same as the conventional grade school approach inspite of doing a lot of work.
Karatsuba multiplication reduces the number of multiplications to 3 which gives us a time complexity of O(nlog3) which is O(n1.58). This may not seem as a huge improvement upfront but even this little improvement saves a lot of time for large values of n.
So in Karatsuba multiplication we calculate,
p1 = x * w
p2 = y * z
p3 = (x + y) * (w + z)
p3 = xw + xz + yw + zy
We can see that we already know the value of xw and yz, hence, we can easily compute xz + yw by subtracting p1 and p2 from p3.
m = p3 - p2 - p1
This allows us to get all the essential values with just 3 basic multiplications rather than 4.
The product now will be given as,
If n is the length of number,
product = 10n * p1 + 10n/2 * m + p2

Implementation

For simplicities sake, this implementation assumes that both the numbers are of same length and the length of digits is only even.
Surprisingly, my implementation works perfectly for 2 digit numbers and to some extent for four digit number, i.e. it's giving wrong output for multiplications like 8344 * 4245 but gives the correct output for multiplication 4443 * 4245.

DISCLAIMER - THIS IMPLEMENTATION IS NOT PERFECT


Comments

  1. Top Online Casino Site in Indonesia - ClickOrCasino
    Check out our reviews on the online casino sites and get the 메리트카지노 best gaming experience. 바카라 ClickorCasino is one of 카지노사이트 the best online casinos in Indonesia!

    ReplyDelete

Post a Comment

Popular Posts

Lambda functions in Python

Lambda functions are simply functions that don't have a name. They are also called anonymous functions and are pretty useful for certain cases. They are extensively used in functional programming . Lambda expression is useful for creating small, one time use functions though the functions can also be given a name. It can have multiple arguments but just a single expression as the function body. The basic syntax to create a lambda function is lambda arguments: function body For example lambda x : x **2 This function takes in x and returns x 2 . Here, lambda is the keyword, x is the argument and the expression after the colon is the function body. These functions can also be given a name, sqr = lambda x : x **2 sqr(5) #output : 25 Multiple arguments can also be provided lambda x,y: x * y or lambda x,y,z: x*y*z These functions when given a name are equivalent to the functions defined by using the def keyword. For example def solve_quad(a,b,c): d = b**2 - (4*a*c) x1 ...

Python for competitive programming

WHY USE PYTHON FOR COMPETITIVE CODING Well a very good reason is that python is a language which radically cuts short the time you spend writing code ,rather you could spend that time thinking about the logic that is needed for the question. In these kind of competitions speed is necessary,I am not talking about the speed of the language but rather about the speed of the programmer.Python syntax is extremely clutter free and elegant which allows us to not get tangled up in complicated details of a programming language. Python also has a very vast variety of tools in its standard library and these tools can be very well utilised in competitive programming. Here's a list of a whole lot of other reasons why you would want to use python: Common inbuilt functions: Python has common functions like count,min,max,sorted etc.These functions allow you to easily go ahead and skip writing code for these trivial procedures which often prove to be very helpful,rest assured: Pytho...

Tuple data structure in Python

Tuple is a linear data structure which more or less behaves like a python list but with a really important difference, that a tuple is immutable . Immutable means that this structure can't be changed after it has been created, it can't be mutated if I may. Tuples being immutable are more memory efficient than list as they don't over allocate memory . Okay, so what this means is, when a list is created it takes up and reserves extra spaces of memory than needed for the original elements as new elements might be added to the list later and allocating memory on every addition would be quite inneficient but tuples, once created surelly won't change the numbers of elements in it later on, so it allocates exactly how much memory is needed. Almost all the list operations work for tuples except the ones which mutate it, for example, insert, append, remove etc. Declaring a tuple : Tuples can be initialise in a manner similar to list, But there's an important c...

Evaluating expressions using Stacks | Dijkstra's Two-Stack Algorithm

We are going to look at Dijkstra's two-stack algorithm and see how it's implemented. This algorithm is used to evaluate infix expressions. It uses stacks at its core, so if you don't know about stacks or if you'd want to learn more about them, click this link There are three types of expressions, Infix : Infix expressions are the ones where the operators are used between values, like a + b - c . Postfix : These are the expressions where operators are written after the values, like a b c +- , this translates to a + b - c in infix. Prefix : In these expressions, the operators are written before the values, for example + - a b c . This expression will also be equal to a + b - c in infix. Okay, so what this algorithm does is evaluate expressions like ( ( 3 + 4 ) * 83 ) . It starts by breaking down this expression into a list of stings and create two empty stack, one for housing the values and other for the operators. Then we go through the list one by one. Whenev...

Random Numbers in Java

In this post we will go through the basics of generating random numbers and also see how they can be generated within a range along with best practices. Java provides support to either generate random numbers through java.lang.Math package or java.util.Random . Using java.lang.Math There exists a static method inside this class, Math.random . It is very convenient to use and returns a double between the range 0.0 and 1.0 i.e. it returns a floating point number between 0 and 1. public static void main(String[] args){ double randNum = Math.random(); System.out.println(randNum); } Random number within a range - To generate a random number within a range we need to further process the number returned by Math.random() public static void main (String[] args){ double min = 10.0; double max = 100.0; double randNum = randRange(min, max); System.out.println(randNum); } public static double randRange(double min, double max){ double x = (Math.rando...

Greedy Algorithms

Greedy Algorithms is an algorithmic paradigm just like divide and conquer is. It is a design technique that depends on locally optimal choices to produce an overall optimal solution. It makes a greedy choice at every step based on a condition and hopes that the choice it made will produce the most optimum solution. A lot of times this technique fails to generate algorithms that are optimal but it does make a lot of problems very very easy. Its used in several different algorithms, most famous of them being: Huffman Coding Dijstrika's Shortest path Kruskal’s Minimum Spanning Tree Greedy algorithms basically make up a solution step by step fashion choosing the next piece which offers the most immediate benefit. Some problems based on Greedy Algorithms are - Grocery Bagger School Assembly Boxing Chopsticks Receipt

Balanced Brackets | Stacks

In this post we will explore and implement an algorithm which helps us verify that if the brackets are balanced or validly used. This is a very important application of stacks as a lot of programming languages use brackets very extensively in their syntax and one of the job of a compiler is to check if the brackets are balanced or not. For simplicity's sake we will just use a list with the methods append() and pop(). This will help us emulate a stack without actually needing to implement it. If you want to, you can go and learn about stacks on this link . A set of brackets can be called balanced if all of the brackets in it are properly matched. Examples of balanced brackets : (([]{}{})) ({{}}[]) Examples of unbalanced brackets : (([)]) {{}]}]]) So now getting to the algorithm, what we simply do is that we go through a string of brackets and check that for every closing bracket there is a properly nested opening bracket. This is how we do it - Convert the input string into a...

Recursion

Recursion What is recursion Three rules of recursion Examples Fibonacci Factorial Additional Resources What is recursion? Recursion is a method of solving problems based on divide and conquer.It is a very elegant way to write solutions to problems that would be pretty inefficient in an iterative solution ( using loops ). A recursive function is basically a function that calls itself on a problem that is somehow smaller or more simplified than the original problem . For example see the function sum of list #Iterative Solution---> 1)def listSum( list ) : 2) sum = 0 3) for i in list : 4) sum += i 5) return sum 1)def listSum( list ) : 2) if len( list ) == 1 : 3) return list[0] 4) else : 5) return list[0] + listSum(list[1:]) In the iterative solution we go through each item in the list and keep adding it to the sum variable . But the same can be solved using a recursive solution . First, in line 2 we check for the base case,that is if the list is...

Kattis | The coding platform

Recently I came across a new website for competitive coding, Kattis and I love it. It is such an amazing platform and has a plethora of question along with multiple long duration contests. The quality of questions is also good and the interface is also very intutive. Follow this link to go to Kattis .