Skip to content

Instantly share code, notes, and snippets.

@Spriithy
Created October 25, 2016 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Spriithy/6135bd980ed27790e3b4204272fbd34c to your computer and use it in GitHub Desktop.
Save Spriithy/6135bd980ed27790e3b4204272fbd34c to your computer and use it in GitHub Desktop.
Find easily if integer N is a perfect square (ie. sqrt(N) is an integer)
func IsPerfectSquare(n int64) bool {
h := n & 0xF; // last hexadecimal "digit"
if h > 9 {
return false
}
// Take advantage of Boolean short-circuit evaluation
if ( h != 2 && h != 3 && h != 5 && h != 6 && h != 7 && h != 8 ) {
t := (int64) (math.Floor(math.Sqrt((float64)(n)) + 0.5 ))
return t * t == n
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment