April 24, 2011

Implementing Division without Divide Operator

Implementing dividing operation is a popular interview question in programmer and software engineering job. When you're asked, of course you must not use divide (/) operator obviously.

Since Multiplication (Devision) is derived from Addition (Subtraction) mathematically, the dividing operation can be implemented using subtraction.

Following function implement the dividing operation. there're two way- using multiplication and subtraction. However, you should use subtraction because multiplication has same property of division. You know devision can be converted to multiplication, and vise versa.



public int divide(int numerator, int denominator) {
int result = 0;

if (numerator == 0)
return numerator;
else if (denominator == 0) {
System.out.println("Error: Divided by 0");
return ERROR;// define constant for ERROR Message
else {
int sign = numerator*denominator > 0? 1:-1;
if(numerator < 0)
numerator *= -1;
if(denominator < 0)
denominator *= -1;
/* using multiplication
while(true) {
result++;
if(result*denominator > numerator) {
result--;
break;
}
}
*/
//using subtraction
while (true) {
numerator = numerator - denominator;
if(numerator>=0)
result++;
else
break;
}

return (sign*result);
}
}