Created
February 14, 2012 08:48
-
-
Save ijt/1824887 to your computer and use it in GitHub Desktop.
Check that n & (n - 1) is non-zero for non-power-of-two numbers
This file contains hidden or 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
import Data.Bits ((.&.)) | |
import Test.QuickCheck (Property, (==>)) | |
prop_bits :: Int -> Property | |
prop_bits n = n > 0 ==> intToBool (n .&. (n - 1)) == not (isPowerOfTwo n) | |
intToBool 0 = False | |
intToBool _ = True | |
isPowerOfTwo :: Int -> Bool | |
isPowerOfTwo x = fromIntegral (truncate l2) == l2 | |
where l2 = log xf / log 2 | |
xf = fromIntegral x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment