views:

64

answers:

4

How to write a function to implement an integer division algorithm without using the division operator. Floating point values and remainders may be discarded. Error conditions may be ignored.

For example:

f(10, 3) is 3

f(10, 5) is 2

f(55, 5) is 11
+2  A: 

My implementation, but it does not take into account signs of operands

function f($value, $div)
{
        $result = 0;
        while ($value >= $div) {
                $result++;
                $value -= $div;
        }

        return $result;
}

var_dump(f(10,3));
zerkms
A: 

My guess is that you will have to look at the bitwise operators $x >> $y shifts one bit to the right (multiplies by two) opposite is $x << $y which shifts one bit to the left thus dividing by two.

sbeskur
+2  A: 
function div($a,$b)
{
   $a -= $a % $b;
   for($i = 0; $a != 0; $i++)
     $a -= $b;
   return $i;
}

this of course only works for positive numbers

DoXicK
+2  A: 

PHP already has a function for that with bcdiv

echo bcdiv(10, 3, 0); // 3
Gordon