Created
September 14, 2013 15:01
-
-
Save ichaos/6562712 to your computer and use it in GitHub Desktop.
Check if a integer is perfect square, i.e. its root is also a 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
bool isPerfectSquare(int x) { | |
int sqr = Math.sqrt(x); | |
return x == sqr * sqr; | |
} | |
bool isPerfectSquareFaster(int x) { | |
if (x < 0) return false; | |
int h = x & 0xf; | |
if (h == 0 || h == 0x1 || h == 0x4 || h == 0x9) { | |
return isPerfectSquare(x); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment