Today I needed a simple algorithm for checking if a number is a power of 2.
The algorithm needs to be:
ulong
Improving the answer of @user134548, without bits arithmetic:
public static bool IsPowerOfTwo(ulong n)
{
if (n % 2 != 0) return false; // is odd (can't be power of 2)
double exp = Math.Log(n, 2);
if (exp != Math.Floor(exp)) return false; // if exp is not integer, n can't be power
return Math.Pow(2, exp) == n;
}
This works fine for:
IsPowerOfTwo(9223372036854775809)