- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements