1 year ago
#296633
Tiến Đình
How to perform division of 2 numbers by inverse multiplication using Bitwise
Here is the code I divide 2 numbers by bit shifting . But I heard there is a faster way, which is to convert division to inverse multiplication.
int divv(int num1, int num2 )
{
bool acc = false;
if(num1<0 && num2>0)
{
num1 = -num1;
acc = true;
}
else if( num1 > 0 && num2 <0)
{
num2 = -num2;
acc = true;
}
else if ( num1 < 0 && num2 <0 )
{
num1 = -num1;
num2 = -num2;
}
int ans = 0;
while(num1 >= num2)
{
long temp = num2, count = 1;
if(temp <= num1)
{
temp <<= 1;
count <<= 1;
}
ans += count >> 1;
num1 -= temp >> 1;
}
return acc?(-ans):(ans);
}
can anyone help me understand the implementation of division by inverse multiplication? Note that only bitwise operators can be used
c
binary
bitwise-operators
division
inverse
0 Answers
Your Answer