Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the product of two integers without using * JavaScript
We are required to write a function that takes in two numbers and returns their product, but without using the (*) operator.
Method 1: Using Division Operator
We know that multiplication and division are inverse operations, so if we divide a number by another number's inverse, it's the same as multiplying the two numbers.
The mathematical concept: a × b = a ÷ (1 ÷ b)
const a = 20, b = 45; const product = (a, b) => a / (1 / b); console.log(product(a, b));
900
Method 2: Using Logarithms
Using the logarithmic property: log(a) + log(b) = log(a × b), we can calculate the product using exponential functions.
const a = 20, b = 45;
const product = (a, b) => {
const logProduct = Math.log(a) + Math.log(b);
return Math.round(Math.exp(logProduct));
};
console.log(product(a, b));
900
Method 3: Using Repeated Addition
For positive integers, multiplication is essentially repeated addition. We can add one number to itself multiple times.
const product = (a, b) => {
if (b === 0) return 0;
let result = 0;
let isNegative = (a
42
-20
0
Comparison
| Method | Works with Decimals | Performance | Handles Negatives |
|---|---|---|---|
| Division Method | Yes | Fast | Yes |
| Logarithms | Yes | Fast | Requires handling |
| Repeated Addition | No (integers only) | Slow for large numbers | Yes |
Conclusion
The division method is the most practical approach for calculating products without the multiplication operator. For educational purposes, repeated addition demonstrates the fundamental concept of multiplication.
