Skip to content

Commit 50c0259

Browse files
committed
Refactor bitwise multiplication.
1 parent 53c7143 commit 50c0259

File tree

3 files changed

+58
-14
lines changed

3 files changed

+58
-14
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import multiplyUnsigned from '../multiplyUnsigned';
2+
3+
describe('multiplyUnsigned', () => {
4+
it('should multiply two unsigned numbers', () => {
5+
expect(multiplyUnsigned(0, 2)).toBe(0);
6+
expect(multiplyUnsigned(2, 0)).toBe(0);
7+
expect(multiplyUnsigned(1, 1)).toBe(1);
8+
expect(multiplyUnsigned(1, 2)).toBe(2);
9+
expect(multiplyUnsigned(2, 7)).toBe(14);
10+
expect(multiplyUnsigned(7, 2)).toBe(14);
11+
expect(multiplyUnsigned(30, 2)).toBe(60);
12+
expect(multiplyUnsigned(17, 34)).toBe(578);
13+
expect(multiplyUnsigned(170, 2340)).toBe(397800);
14+
});
15+
});

src/algorithms/math/bits/multiply.js

-14
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Multiply to unsigned numbers using bitwise operator.
3+
*
4+
* The main idea of bitwise multiplication is that every number may be split
5+
* to the sum of posers of two:
6+
*
7+
* I.e. 19 = 2^4 + 2^1 + 2^0
8+
*
9+
* Then multiplying number x by 19 is equivalent of:
10+
*
11+
* x * 19 = x * 2^4 + x * 2^1 + x * 2^0
12+
*
13+
* Now we need to remember that (x * 2^4) is equivalent of shifting x left by 4 bits (x << 4).
14+
*
15+
* @param {number} number1
16+
* @param {number} number2
17+
* @return {number}
18+
*/
19+
export default function multiplyUnsigned(number1, number2) {
20+
let result = 0;
21+
22+
// Let's treat number2 as a multiplier for the number1.
23+
let multiplier = number2;
24+
25+
// Multiplier current bit index.
26+
let bitIndex = 0;
27+
28+
// Go through all bits of number2.
29+
while (multiplier !== 0) {
30+
// Check if current multiplier bit is set.
31+
if (multiplier & 1) {
32+
// In case if multiplier's bit at position bitIndex is set
33+
// it would mean that we need to multiply number1 by the power
34+
// of bit with index bitIndex and then add it to the result.
35+
result += (number1 << bitIndex);
36+
}
37+
38+
bitIndex += 1;
39+
multiplier >>= 1;
40+
}
41+
42+
return result;
43+
}

0 commit comments

Comments
 (0)