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.");
}
}