Created
October 25, 2016 20:56
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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