Growing with the Web

Integer division without the division operator (/)

Published , updated
Tags:

This article looks at the interview question - Implement a function that performs integer division on two integers without the use of the division / operator. For example for the input of 10 and 4 should result in the output of 2.

Analysis

If you have not thought about this problem before you may be a little taken aback. It’s actually a fairly simple problem, just think about what division actually does; it counts how much of a certain number (the divisor) makes up another number (the dividend). One way we could do this using the subtraction operator (-) is to count how many times you can subtract the divisor from the dividend before 0 is reached.

There are two other cases we need to handle; when the divisor is 0 and when either or both numbers are negative. When the divisor is 0 a good course of action is to throw an exception. For negative numbers, if either value is negative then the result will be negative, if both values are negative then the result will be positive.

Code

public static double divide(double a, double b) {
    if (b == 0) {
        throw new ArithmeticException(
                "Division by 0 is undefined: " + a + "/" + b);
    }
    int sign = 1;
    if (a < 0) {
        a = -a;
        sign = -sign;
    }
    if (b < 0) {
        b = -b;
        sign = -sign;
    }
    double result = 0;
    while (a >= 0) {
        a -= b;
        result++;
    }
    return (result - 1) * sign;
}
function integerDivideWithoutDivide(a, b) {
  if (b === 0) {
    throw 'Division by zero is undefined: ' + a + '/' + b;
  }
  var sign = 1;
  if (a < 0) {
    a = -a;
    sign = -sign;
  }
  if (b < 0) {
    b = -b;
    sign = -sign;
  }
  var result = 0;
  while (a >= 0) {
    a -= b;
    result++;
  }
  return (result - 1) * sign;
}

Textbooks

Here are two textbooks that provide many Q&A's like this post that I personally recommend, both were invaluable to me when I was studying for my interviews.

 

Like this article?
Subscribe for more!