dist-javascript-algorithms-and-data-structures
Version:
Algorithms and data-structures implemented on JavaScript
55 lines (42 loc) • 1.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = multiply;
var _multiplyByTwo = _interopRequireDefault(require("./multiplyByTwo"));
var _divideByTwo = _interopRequireDefault(require("./divideByTwo"));
var _isEven = _interopRequireDefault(require("./isEven"));
var _isPositive = _interopRequireDefault(require("./isPositive"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Multiply two signed numbers using bitwise operations.
*
* If a is zero or b is zero or if both a and b are zeros:
* multiply(a, b) = 0
*
* If b is even:
* multiply(a, b) = multiply(2a, b/2)
*
* If b is odd and b is positive:
* multiply(a, b) = multiply(2a, (b-1)/2) + a
*
* If b is odd and b is negative:
* multiply(a, b) = multiply(2a, (b+1)/2) - a
*
* Time complexity: O(log b)
*
* @param {number} a
* @param {number} b
* @return {number}
*/
function multiply(a, b) {
// If a is zero or b is zero or if both a and b are zeros then the production is also zero.
if (b === 0 || a === 0) {
return 0;
} // Otherwise we will have four different cases that are described above.
const multiplyByOddPositive = () => multiply((0, _multiplyByTwo.default)(a), (0, _divideByTwo.default)(b - 1)) + a;
const multiplyByOddNegative = () => multiply((0, _multiplyByTwo.default)(a), (0, _divideByTwo.default)(b + 1)) - a;
const multiplyByEven = () => multiply((0, _multiplyByTwo.default)(a), (0, _divideByTwo.default)(b));
const multiplyByOdd = () => (0, _isPositive.default)(b) ? multiplyByOddPositive() : multiplyByOddNegative();
return (0, _isEven.default)(b) ? multiplyByEven() : multiplyByOdd();
}