Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add karatsuba algorithm #225

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
finish README
appleJax committed Oct 18, 2018
commit 0cdb6b3798a369f47eb843235a848ff416605a93
36 changes: 35 additions & 1 deletion src/algorithms/math/karatsuba-multiplication/README.md
Original file line number Diff line number Diff line change
@@ -2,6 +2,40 @@

Karatsuba is a fast multiplication algorithm discovered by Anatoly Karatsuba in 1960. Given two n-digit numbers, the "grade-school" method of long multiplication has a time complexity of O(n<sup>2</sup>), whereas the karatsuba algorithm has a time complexity of O(n<sup>1.59</sup>).

## Recursive Formula

```
x = 1234
y = 5678
karatsuba(x, y)
```

1. Split each number into numbers with half as many digits
```
a = 12
b = 34
c = 56
d = 78
```

2. Compute 3 subexpressions from the smaller numbers
- `ac = a * c`
- `bd = b * d`
- `abcd = (a + b) * (c + d)`

3. Combine subexpressions to calculate the product
```
A = ac * 1000
B = (abcd - ac - bd) * 100
C = bd
x * y = A + B + C
```

_**Note:**_ *The karatsuba algorithm can be applied recursively to calculate each product in the subexpressions.* (`a * c = karatsuba(a, c)`*). When the numbers get smaller than some arbitrary threshold, they are multiplied in the traditional way.*

## References
[Stanford Algorithms (YouTube)](https://www.youtube.com/watch?v=JCbZayFr9RE)
[Wikipedia](https://en.wikipedia.org/wiki/Karatsuba_algorithm)
[Wikipedia](https://en.wikipedia.org/wiki/Karatsuba_algorithm)