C# 二分查找求平方根

       static int Sqrt1(int num)
{
if (num < 0)
{
throw new Exception(num + " doesn't have square root.");
}

if (num == 1)
{
return num;
}
int low = 0;
int high = num;
int temp = (low + high) / 2;
int sign = temp;
checked
{
while (Math.Abs(temp * temp - num) > 1)
{
sign = temp;
if (temp * temp > num)
{
high = temp;
}
else
{
low = temp;
}
temp = (low + high) / 2;
if (sign == temp)
{
break;
}
}
}
if (temp * temp == num)
{
return temp;
}
else
{
throw new Exception(num + " doesn't have integer square root.");
}
}
posted @ 2012-02-10 07:44  Ligeance  阅读(1047)  评论(0编辑  收藏  举报