您的位置:首页 > 编程语言

9、编程实现两个正整数的除法

2012-09-05 20:23 706 查看
/************************************************************************/
/* 9、编程实现两个正整数的除法                                            */
/************************************************************************/
// abs(x)/abs(y) = h, 则 (h+1)* abs(y) > abs(x) >= h * y, 利用二分查找求h
//找到满足条件的k, 时间复杂度o(1)
int div1(const int x, const int y)
{
if(y == 0)
throw new exception("divided by zero!");
if(x == 0)
return 0;

//保证x、y可以去到0xffffffff
unsigned tempX = abs(x);
unsigned tempY = abs(y);

unsigned h = 1;
unsigned hy = tempY;
//最多32次
while(hy < tempX)
{
hy <<= 1;        //tempY * 2
h <<= 1;
}
//最多31次
//result一定在[h/2, h)之间 [l, h)
unsigned l = h >> 1;
while(l < h - 1)
{
unsigned mid = (l + h) >> 1;           //(l +h) /2
unsigned midy = mid * tempY;
if(midy == tempX)
{
l = mid;
break;
}
else if(midy < tempX)
l = mid;
else
h = mid;
}
//判断符号
if((x > 0 && y < 0) || (x < 0 && y > 0))
return -1 * l;
else
return l;
}
void testOfDiv()
{
int x = rand() % 1000000;
int y = rand()% 10000000;
int ret1= 0;
cout << "x/y" << endl;
CLOCK
{
ret1 = x / y;
}
int ret2 = 0;
cout << "div1(x/y)" << endl;
CLOCK
{
ret2 = div1(x, y);
}
assert(ret1 == ret2);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: