|
| 1 | +import multiplyByTwo from './multiplyByTwo'; |
1 | 2 | import divideByTwo from './divideByTwo';
|
2 | 3 | import isEven from './isEven';
|
3 |
| -import multiplyByTwo from './multiplyByTwo'; |
4 | 4 |
|
5 | 5 | /**
|
6 |
| - * FUNCTION DEFINITION |
7 |
| - * multiply(a, b) = 0 if a is zero or b is zero or if both a and b are zeros |
8 |
| - * multiply(a, b) = multiply(2a, b/2) if b is even |
9 |
| - * multiply(a, b) = multiply(2a, (b-1)/2) + a if b is odd and b is positive |
10 |
| - * multiply(a, b) = multiply(2a, (b+1)/2) - a if b is odd and b is negative |
| 6 | + * Multiply two signed numbers using bitwise operations. |
| 7 | + * |
| 8 | + * If a is zero or b is zero or if both a and b are zeros: |
| 9 | + * multiply(a, b) = 0 |
| 10 | + * |
| 11 | + * If b is even: |
| 12 | + * multiply(a, b) = multiply(2a, b/2) |
| 13 | + * |
| 14 | + * If b is odd and b is positive: |
| 15 | + * multiply(a, b) = multiply(2a, (b-1)/2) + a |
| 16 | + * |
| 17 | + * If b is odd and b is negative: |
| 18 | + * multiply(a, b) = multiply(2a, (b+1)/2) - a |
| 19 | + * |
| 20 | + * Time complexity: O(log b) |
11 | 21 | *
|
12 |
| - * COMPLEXITY |
13 |
| - * O(log b) |
14 | 22 | * @param {number} a
|
15 | 23 | * @param {number} b
|
16 |
| - * @return {number} a * b |
| 24 | + * @return {number} |
17 | 25 | */
|
18 | 26 | export default function multiply(a, b) {
|
| 27 | + // If a is zero or b is zero or if both a and b are zeros then the production is also zero. |
19 | 28 | if (b === 0 || a === 0) {
|
20 | 29 | return 0;
|
21 | 30 | }
|
22 | 31 |
|
| 32 | + // Otherwise we will have four different cases that are described above. |
23 | 33 | const multiplyByOddPositive = () => multiply(multiplyByTwo(a), divideByTwo(b - 1)) + a;
|
24 | 34 | const multiplyByOddNegative = () => multiply(multiplyByTwo(a), divideByTwo(b + 1)) - a;
|
| 35 | + |
25 | 36 | const multiplyByEven = () => multiply(multiplyByTwo(a), divideByTwo(b));
|
26 | 37 | const multiplyByOdd = () => (b > 0 ? multiplyByOddPositive() : multiplyByOddNegative());
|
27 | 38 |
|
|
0 commit comments