how to write a function to implement an integer division algorithm without using the division operator in php [closed]
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.
精彩评论