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.

Trick 1: Using Divide Operator Twice

We know that multiplication and division are just the inverse of each other, so if we divide a number by other number’s inverse, won’t it be same as multiplying the two numbers?

Let’s see the code for this −

const a = 20, b = 45;
const product = (a, b) => a / (1 / b);
console.log(product(a, b));

Trick 2: Using Logarithms

Let’s examine the properties of logarithms first −

log(a) + log(b) = log(ab)

So, let’s use this property of logarithms to our good. The code for this will be −

Example

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));

Output

The output in the console for both will be −

900

Updated on: 19-Aug-2020

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements