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

来源:互联网 发布:山西八建集团网络平台 编辑:程序博客网 时间:2024/06/06 17:54
/************************************************************************//* 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可以去到0xffffffffunsigned tempX = abs(x);unsigned tempY = abs(y);unsigned h = 1;unsigned hy = tempY;//最多32次while(hy < tempX){hy <<= 1;        //tempY * 2h <<= 1;}//最多31次//result一定在[h/2, h)之间 [l, h)unsigned l = h >> 1;while(l < h - 1){unsigned mid = (l + h) >> 1;           //(l +h) /2unsigned midy = mid * tempY;if(midy == tempX){l = mid;break;}else if(midy < tempX)l = mid;elseh = mid;}//判断符号if((x > 0 && y < 0) || (x < 0 && y > 0))return -1 * l;elsereturn 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);}

原创粉丝点击