Quantcast
Viewing all articles
Browse latest Browse all 38

Answer by Raz Megrelidze for How to check if a number is a power of 2

    bool IsPowerOfTwo(int n)    {        if (n > 1)        {            while (n%2 == 0)            {                n >>= 1;            }        }        return n == 1;    }

And here's a general algorithm for finding out if a number is a power of another number.

    bool IsPowerOf(int n,int b)    {        if (n > 1)        {            while (n % b == 0)            {                n /= b;            }        }        return n == 1;    }

Viewing all articles
Browse latest Browse all 38

Trending Articles