开发者

how to write a function to implement an integer division algorithm without using the division operator in php [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly a开发者_运维百科pplicable, visit the help center. Closed 10 years ago.

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


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


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));


PHP already has a function for that with bcdiv

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜