DEV Community

How to divide two numbers in JavaScript with out using the "/" operator?

Ticha Godwill Nji on April 13, 2024

Here're some tips on how to divide numbers in javascript without using the "/" operator. This is a very efficacy method. Which means that it has ju...
Collapse
 
avikki profile image
AviKKi

Alternatively you can do a binary search for the solution in range 0 to dividend in log(n) time

Collapse
 
ticha profile image
Ticha Godwill Nji

Thank you for your comment! Yes, using binary search for division can indeed provide a more efficient solution, especially for large dividends. It's a great way to optimize the algorithm and reduce computation time. I appreciate you highlighting this approach!

Collapse
 
avikki profile image
AviKKi

Alternatively you can do a binary search for the solution in range 0 to dividend

Collapse
 
ticha profile image
Ticha Godwill Nji

Absolutely, it can be used in the** while loop**.
There are many methods that can be used to in accomplish this same results.

Binary

while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (mid * divisor <= dividend) {
quotient = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}

Collapse
 
citronbrick profile image
CitronBrick • Edited

you can enable syntax highlighting through:

triple backtick javascript
code
triple backtick

Collapse
 
ticha profile image
Ticha Godwill Nji • Edited

Thanks for letting me know Buddy!

Collapse
 
jonrandy profile image
Jon Randy 🎖️

You could also use logarithms

Collapse
 
ticha profile image
Ticha Godwill Nji • Edited

Thank you for your comment! It's a great way to optimize the algorithm and reduce computation time. I appreciate you highlighting this approach!

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

? I never mentioned binary search

// Calculate a/b without /
Math.exp(Math.log(a) - Math.log(b))
Enter fullscreen mode Exit fullscreen mode

Yes, you'll need some code to handle negative numbers, but this highlights the main approach

Collapse
 
jonrandy profile image
Jon Randy 🎖️
let a = 5
a /= 2
Enter fullscreen mode Exit fullscreen mode

I didn't use the / operator :)

Collapse
 
kapenike profile image
Spencer

I like it! I wonder if there is a way to speed this up by wrapping the negative number handling into the math 🤔

Collapse
 
ticha profile image
Ticha Godwill Nji

That's a great idea! Handling negative numbers within the mathematical calculations can streamline the code and potentially improve its efficiency. One way to achieve this is by leveraging the absolute values of the dividend and divisor during the binary search process, and then adjusting the sign of the quotient accordingly. This approach avoids the need for separate handling of negative numbers.