Skip to content

Instantly share code, notes, and snippets.

@jonnyli1125
Created December 2, 2012 10:29
Show Gist options
  • Save jonnyli1125/4188092 to your computer and use it in GitHub Desktop.
Save jonnyli1125/4188092 to your computer and use it in GitHub Desktop.
Integer Square Root
public static int IntSqrt(int num) // Faster than Math.Sqrt, because that uses doubles.
{
if (num < 0) throw new Exception("Cannot get square root of negative number.");
if (0 == num) return 0; // Avoid zero divide
int n = (num / 2) + 1; // Initial estimate, never low
int n1 = (n + (num / n)) / 2;
while (n1 < n)
{
n = n1;
n1 = (n + (num / n)) / 2;
}
return n;
}
@zhuowei
Copy link

zhuowei commented Apr 28, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment