Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 42b5a46

Browse files
committedOct 18, 2018
add karatsuba multiplication algorithm
1 parent fad170c commit 42b5a46

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed
 

‎src/algorithms/math/karatsuba-multiplication/README.md

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import karatsuba from '../karatsuba';
2+
3+
describe('karatsuba multiplication', () => {
4+
xit('should multiply numbers correctly', () => {
5+
expect(karatsuba(1234, 5678)).toEqual(7006652);
6+
});
7+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
*
3+
* @param {number} x
4+
* @param {number} y
5+
* @return {number}
6+
*/
7+
export default function karatsuba(x, y) {
8+
// BASE CASE:
9+
// if numbers are sufficiently small,
10+
// multiply them together in the traditional way
11+
if (x < 10 || y < 10) {
12+
return x * y;
13+
}
14+
15+
const minDigits = Math.min(
16+
String(x).length,
17+
String(y).length,
18+
);
19+
20+
// scaleFactor is used to split the numbers
21+
// into smaller numbers for recursion.
22+
// when combining the subcomputations back
23+
// together, the scaleFactor is used to
24+
// recreate the components of the original number
25+
const scaleFactor = 10 ** Math.floor(minDigits / 2);
26+
27+
// a b are the two components of x
28+
// c d are the two components of y
29+
//
30+
// e.g.
31+
// x = 1234 -> a = 12, b = 34
32+
// y = 5678 -> c = 56, d = 78
33+
//
34+
// example of component computations:
35+
// x = 1234, y = 5678
36+
// scaleFactor = 100
37+
// a = floor(1234 / 100) = floor(12.34) = 12
38+
const a = Math.floor(x / scaleFactor);
39+
40+
// b = 1234 - (12 * 100) = 1234 - 1200 = 34
41+
const b = x - (a * scaleFactor);
42+
43+
// c = floor(5678 / 100) = floor(56.78) = 56
44+
const c = Math.floor(y / scaleFactor);
45+
46+
// d = 5678 - (56 * 100) = 5678 - 5600 = 78
47+
const d = y - (c * scaleFactor);
48+
49+
// compute sub-expressions:
50+
// since a + b is less than x, and c + d is less than y
51+
// the recursion is guaranteed to reach the base case
52+
const ac = karatsuba(a, c);
53+
const bd = karatsuba(b, d);
54+
const abcd = karatsuba(a + b, c + d);
55+
56+
// combine sub-expressions:
57+
// since the scaleFactor was used to
58+
// artificially reduce the size of the components,
59+
// the scaleFactor must be applied in reverse
60+
// to reconstruct the original components
61+
const A = ac * (scaleFactor ** 2);
62+
const B = (abcd - ac - bd) * scaleFactor;
63+
const C = bd;
64+
65+
return A + B + C;
66+
}

0 commit comments

Comments
 (0)
Please sign in to comment.