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

RMAG news

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 just a few steps.

I will use ES6 syntax for writing my code.

const divide = (dividend, divisor) => {
if (divisor === 0) {
throw new Error(“Division by zero is not allowed.”);
}

let quotient = 0;
let isNegative = false;

if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) {
isNegative = true;
}

dividend = Math.abs(dividend);
divisor = Math.abs(divisor);

while (dividend >= divisor) {
dividend -= divisor;
quotient++;
}

if (isNegative) {
quotient = -quotient;
}

return quotient;
}

// Test the divide function
console.log(divide(10, 1)); // Output should be 5
console.log(divide(7, 3)); // Output should be 2
console.log(divide(10, -2)); // Output should be -5
console.log(divide(-7, 3)); // Output should be -2
console.log(divide(0, 5)); // Output should be 0
console.log(divide(2, 10)); // Output should be 0

Breakdown

First, we declare the function divide and pass the dividend and divisor as parameters.

In the function block, we start by checking if the divisor is equal to zero. If that is true, we throw an error message.

The next step is to declare the quotient and assign it to zero, and isNegative and assign it the value of false.

We then check if any of the numbers is less than zero, which makes isNegative return true.

If isNegative returns true, we take the absolute value of the numbers to convert them to positive numbers by using the JS built-in Math.abs().

We now enter a while loop that keeps subtracting the divisor from the dividend, and the quotient is incremented.

If isNegative is true, the quotient should be multiplied by **-1 **and returned as our result.

Leave a Reply

Your email address will not be published. Required fields are marked *